如果我点击文字字段(html表单)来写一些东西,我该如何清空它。
伪代码:
On click #searchform
Erase String in #searchform
答案 0 :(得分:5)
$('#searchform').click(function() { $(this).val('') })
答案 1 :(得分:4)
$('#searchform').click(function() {
if ($(this).val() == 'Enter search term') {
$(this).data('original', $(this).val()).val('');
}
});
$('#searchform').blur(function() {
if ($(this).val() == '') {
$(this).val($(this).data('original'));
}
});
编辑截至目前,您应该使用placeholder属性,如果需要,可以使用上面的填充作为缺少占位符支持的填充。
if (!('placeholder' in document.createElement('input'))){
$('input[placeholder]').each(function() {
$(this).placeholder();
});
}
将原始代码转换为插件以便于使用(使用一些小mod)。
jQuery.fn.placeholder = function() {
return this.each(function() {
var value = $(this).attr('placeholder');
jQuery(this).val(value).addClass('placeholder');
jQuery(this).focus(function() {
if (jQuery(this).val() == value) {
jQuery(this).val('').removeClass('placeholder');
}
});
jQuery(this).blur(function() {
if (jQuery(this).val() == '') {
jQuery(this).val(value).addClass('placeholder');
}
});
});
};
答案 2 :(得分:3)
我建议您使用HTML5占位符属性。例如:
<input type="text" placeholder="some default string if empty" />
这适用于大多数最新的浏览器,对于较旧的浏览器,有一个解决方法jQuery插件。以下是placeholder plugin的链接。
然后你只需致电:
$('input[placeholder]').placeholder();
答案 3 :(得分:1)
如果您想要清除某个字段的默认值,例如“输入搜索字词”,请使用以下代码:
function clearText(thefield){
if (thefield.defaultValue==thefield.value)
thefield.value = ""
}
然后在我的输入字段中添加:
onfocus="clearText(this)"
所以它会是:
<input type="text" name="username" value="enter your name here" onfocus="clearText(this)">