Javascript:this.value函数不工作

Javascript:this.value函数不工作,javascript,html,function,input,Javascript,Html,Function,Input,好的,我有以下功能: function hideValue(value) { if (this.value == value) { this.value = ''; } <input onfocus="hideValue(this,'First Name') /* 'this' is only correct here */" type="text" name="first_name" value="First Name" > 以及以下表单字段: &

好的,我有以下功能:

function hideValue(value) {
    if (this.value == value) {
       this.value = '';
}
<input
  onfocus="hideValue(this,'First Name') /* 'this' is only correct here */"
  type="text" name="first_name" value="First Name"
>
以及以下表单字段:

<input onfocus="hideValue('First Name')" type="text" name="first_name" value="First Name">

我无法获取隐藏该值的函数。当I
alert(值)时
我还有一个showValue函数,它的作用正好相反。为什么这些功能不起作用?

我建议将其用于此类功能

<input type="text" name="first_name" placeholder="First Name" />
                                     ^^^^^^^^^^^^^^^^^^^^^^^^

^^^^^^^^^^^^^^^^^^^^^^^^

演示:

我建议将其用于此类功能

<input type="text" name="first_name" placeholder="First Name" />
                                     ^^^^^^^^^^^^^^^^^^^^^^^^

^^^^^^^^^^^^^^^^^^^^^^^^

演示:


在DOM元素的事件处理程序中,此
仅在函数的第一级引用元素。因此,您需要将此传递到函数中:

function hideValue(value) {
    if (this.value == value) {
       this.value = '';
}
<input
  onfocus="hideValue(this,'First Name') /* 'this' is only correct here */"
  type="text" name="first_name" value="First Name"
>

在DOM元素
上的事件处理程序中,该
仅在函数的第一级引用该元素。因此,您需要将此
传递到函数中:

function hideValue(value) {
    if (this.value == value) {
       this.value = '';
}
<input
  onfocus="hideValue(this,'First Name') /* 'this' is only correct here */"
  type="text" name="first_name" value="First Name"
>

函数hideValue(thisvalue,value){
if(thisvalue.value==值){
thisvalue.value='';
}
}
请检查这个。工作正常


函数hideValue(thisvalue,value){
if(thisvalue.value==值){
thisvalue.value='';
}
}

请检查这个。其工作正常

当您以这种方式调用函数时,此
不引用元素(因此,
此.value
可能未定义)。请注意,缺少一个右括号,这将导致语法错误。回答者应该在他们的回答中意识到这一点。它在我的代码里,但不在帖子里。感谢所有回应的人,现在有意义了
this
以这种方式调用函数时不引用元素(因此
this.value
可能未定义)。请注意,缺少一个右括号,这将导致语法错误。回答者应该在他们的回答中意识到这一点。它在我的代码里,但不在帖子里。感谢所有回应的人,现在有意义了!这比使用占位符有什么好处吗?或者占位符是更好的做法吗?@TimothyFisher
placeholder
是实现此类功能的最佳方式,除非您想支持granny的代浏览器。谢谢Tushar!我将此标记为解决方案,因为这是我第一次看到使函数工作的解决方案。这个占位符建议我可能会同意@提摩太鱼没问题。我很高兴你会使用占位符(占位符)这比使用占位符有什么好处吗?或者占位符是更好的做法吗?@TimothyFisher
placeholder
是实现此类功能的最佳方式,除非您想支持granny的代浏览器。谢谢Tushar!我将此标记为解决方案,因为这是我第一次看到使函数工作的解决方案。这个占位符建议我可能会同意@提摩太鱼没问题。我很高兴您能使用
占位符
:)