Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么attr方法在这种情况下不起作用?_Javascript_Jquery_Html - Fatal编程技术网

Javascript 为什么attr方法在这种情况下不起作用?

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

我试图让这个输入在我点击它时清除它的值,但是我没有得到任何结果

HTML:

<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;
}