I'm using this code from here: http://jsfiddle.net/davidThomas/9BpGC/
But as an external JS file.
I have:
<input type="text" id="text1" name="text1" placeholder="First text input box." onfocus="clearText()" />
External JS:
function clearText()
{
$('input:text').each(
function(){
$(this)
.val($(this).attr('placeholder'))
.css('color','#999');
$(this).click(
function(){
$(this)
.val('')
.css('color','#000');
});
$(this).blur(
function(){
if ($(this).val() === ''){
$(this)
.val($(this).attr('placeholder'))
.css('color','#999');
}
开发者_StackOverflow中文版});
}
);
}
It works in FF5, Chrome but not in IE8 unless I click in the box to load the search hint - if you use the demo on jsFiddle, it works fine across the different browsers, so is there a way to fix it to work with an external JS?
My guess: it doesn't have to do with the externality of the file, but your implementation.
Rather than putting this logic inside of a function (clearText()
) in this case, you should really put it in $(document).ready
; this logic only needs to happen once, and it should happen when the document is ready (this is how the JSFiddle does it). Your code should look something more like this:
$(document).ready(function() {
// Placeholder text logic
$('input:text').each(function() {
// the code you already have
});
});
That is the only apparent difference between what you're doing and what that example does.
精彩评论