我在这里使用此代码:http://jsfiddle.net/davidThomas/9BpGC/
但是作为外部JS文件。
我有:
<input type="text" id="text1" name="text1" placeholder="First text input box." onfocus="clearText()" />
外部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');
}
});
}
);
}
它适用于FF5,Chrome但不适用于IE8,除非我在框中单击以加载搜索提示 - 如果您在jsFiddle上使用该演示,它可以在不同的浏览器中正常工作,那么有没有办法将其修复为使用外部JS?
答案 0 :(得分:1)
我的猜测:它与文件的外部性无关,而是与您的实现有关。
在这种情况下,不应该将此逻辑放在函数(clearText()
)中,而应该将它放在$(document).ready
中;这个逻辑只需要发生一次,它应该在文档准备就绪时发生(这就是the JSFiddle这样做的原因)。您的代码看起来应该更像这样:
$(document).ready(function() {
// Placeholder text logic
$('input:text').each(function() {
// the code you already have
});
});
这是你正在做的和那个例子之间唯一明显的区别。