Javascript 清除文本 onclick - 文本字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2851794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:11:17  来源:igfitidea点击:

clear text onclick - textfield

javascripthtml

提问by tony noriega

What is the best method to clear text in a text field, when the user clicks on it?

当用户单击文本字段中的文本时,清除文本的最佳方法是什么?

I.e., if the text search field says "search" and when they click it, it clears the value.

即,如果文本搜索字段显示“搜索”并且当他们单击它时,它会清除该值。

回答by Sarfraz

You could do like:

你可以这样做:

<input type="text" onfocus="if(this.value == 'search') {this.value=''}" onblur="if(this.value == ''){this.value ='search'}">

回答by Damon Pace

<input name="foo" placeholder="Search" />The placeholder tag is a new HTML5 tag that does exactly what you want to do here.

<input name="foo" placeholder="Search" />占位符标签是一个新的 HTML5 标签,它完全符合您在此处想要执行的操作。

回答by Jason

Normal HTML:

普通 HTML:

 <script type="text/javascript">
    function clearThis(target){
        target.value= "";
    }
    </script>
    <input type="text" value="Search" onfocus="clearThis(this)" />

jQuery:

jQuery:

<script type="text/javascript">
    function clearThis(target){
        $(target).val = "";
    }
</script>
<input type="text" value="Search" onfocus="clearThis(this)" />

回答by AlexCuse

If jquery's an option, I'd consider the watermark plugin

如果 jquery 是一个选项,我会考虑水印插件

It achieves what you're after, but with a bit more style

它实现了您所追求的目标,但更具风格

回答by Oded

In JavaScript you can simple set the value of the contorol to an empty string in the OnFocus event handler.

在 JavaScript 中,您可以在 OnFocus 事件处理程序中简单地将控制值设置为空字符串。