1

如果我单击它来写东西,如何清空文本字段(html 表单)。

伪代码:

On click #searchform
Erase String in #searchform
4

4 回答 4

5
$('#searchform').click(function() { $(this).val('') })
于 2010-11-18T08:35:27.593 回答
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属性,如果需要,可以使用上面的内容作为缺少占位符支持的 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');
            }
        });
    });
};
于 2010-11-18T08:42:18.753 回答
3

我建议您使用 HTML5 占位符属性。例如:

<input type="text" placeholder="some default string if empty" />

这适用于大多数最新的浏览器,对于较旧的浏览器,有一个解决方法 jQuery 插件。这是占位符插件的链接。

然后你只需调用:

$('input[placeholder]').placeholder();
于 2010-11-18T08:46:56.503 回答
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)">
于 2010-11-18T08:46:18.997 回答