Javascript 为什么attr方法在这种情况下不起作用?
我试图让这个输入在我点击它时清除它的值,但是我没有得到任何结果 HTML:Javascript 为什么attr方法在这种情况下不起作用?,javascript,jquery,html,Javascript,Jquery,Html,我试图让这个输入在我点击它时清除它的值,但是我没有得到任何结果 HTML: <input id='input' type="text" name="phppostvar" value="clear this"></input> $('#input').click(function(){ var value = $('#input').attr('value'); if (value === "clear this") { $('#in
<input id='input' type="text" name="phppostvar" value="clear this"></input>
$('#input').click(function(){
var value = $('#input').attr('value');
if (value === "clear this") {
$('#input').attr('value','');
}
});
我只想使用
占位符
属性,或者一个非常简单的JS解决方案:
document.getElementById("input").onfocus = function() {
this.value = this.value == "clear this" ? "" : this.value;
}
我会尝试使用.val()而不是.attr('value','')或使用
占位符
属性每当用户单击输入时移动值是个糟糕的主意。他们可能会在几个特定的字母之间点击以更正打字错误。您的示例确实有效。可能不建议使用,但您可以在此处看到它的工作原理:
document.getElementById("input").onfocus = function() {
this.value = this.value == "clear this" ? "" : this.value;
}