javascript 如何启用 onclick 以清除输入字段?查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4587105/
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
How can do I enable onclick to clear an input field? Jquery
提问by user113716
$('<p><input type="text" class = "class-'+ (++i) +'" onclick="'(+ this.value = ''; +)'" value="Enter Choice #' + i + '"/></p>')
I'm not sure if this is the correct syntax or not, but whatever I am using is not working. ANy help? Thanks
我不确定这是否是正确的语法,但无论我使用什么都不起作用。有什么帮助吗?谢谢
回答by PeeHaa
HTML:
HTML:
<input type="text" class="class-1" value="Enter Choice #1">
<input type="text" class="class-2" value="Enter Choice #2">
JQUERY:
查询:
$(document).ready(function() {
$('input[class^="class-"]').focus(function() {
var $input = $(this);
if($input.val() == $input.data('default_val') || !$input.data('default_val')) {
$input.data('default_val', $input.val());
$input.val('');
}
});
$('input[class^="class-"]').blur(function() {
var $input = $(this);
if ($input.val() == '') $input.val($input.data('default_val'));
});
});
Above code clear the value when the textfields gets focus and adds the default value when textfield is empty on lost focus (blur).
上面的代码在文本字段获得焦点时清除值,并在失去焦点(模糊)时文本字段为空时添加默认值。
Updated fiddle: http://jsfiddle.net/K3Sx7/4/
更新小提琴:http: //jsfiddle.net/K3Sx7/4/
EDIT: updated code to conform question.
编辑:更新代码以符合问题。
回答by Yuri Ghensev
Add an id to your input field:
将 id 添加到您的输入字段:
<input id="myinput"...
Then add this code in your $(document).ready(...call:
然后在您的$(document).ready(...通话中添加此代码:
$('#myinput') // get element whose id is 'myinput'
.click(function() { // bind a click handler
$(this).val('') // clear field
.unbind('click'); // unbind click handler to avoid field being cleared again
})
回答by shankhan
I think you can do it without jQuery try this
我认为你可以在没有 jQuery 的情况下做到这一点试试这个
<p><input type="text" class = "class-1" onclick="this.value='';" value="Enter Choice # 1"/></p>
回答by Josiah Ruddell
var i = 0;
$('<input type="text" class="class-'+ ++i +'" value="Enter Choice #' + i + '"/>')
.click(function(){
this.value = '';
})
.wrap('<p />')
.parent()
.appendTo('#container');
回答by user113716
To do it inline like that, you need to keep the this.value=''as part of the string:
要这样做内联,您需要保留this.value=''作为字符串的一部分:
$('<p><input type="text" class = "class-'+ (++i) +'" onclick="this.value=\'\'" value="Enter Choice #' + i + '"/></p>');
Notice the " onclick="this.value=\'\'", where the single quotes are escaped to keep the main string from being terminated.
注意" onclick="this.value=\'\'", 单引号被转义以防止主字符串被终止。

