如果我单击它来写东西,如何清空文本字段(html 表单)。
伪代码:
On click #searchform
Erase String in #searchform
如果我单击它来写东西,如何清空文本字段(html 表单)。
伪代码:
On click #searchform
Erase String in #searchform
$('#searchform').click(function() { $(this).val('') })
$('#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属性,如果需要,可以使用上面的内容作为缺少占位符支持的 polyfill。
if (!('placeholder' in document.createElement('input'))){
$('input[placeholder]').each(function() {
$(this).placeholder();
});
}
并将原代码转成插件方便使用(配合一些小模组)。
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');
}
});
});
};
我建议您使用 HTML5 占位符属性。例如:
<input type="text" placeholder="some default string if empty" />
这适用于大多数最新的浏览器,对于较旧的浏览器,有一个解决方法 jQuery 插件。这是占位符插件的链接。
然后你只需调用:
$('input[placeholder]').placeholder();
如果您想从诸如“输入搜索词”之类的字段中清除默认值,我使用以下代码:
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)">