gpt4 book ai didi

Javascript:this.value 函数不工作

转载 作者:行者123 更新时间:2023-11-28 04:49:17 28 4
gpt4 key购买 nike

好的,所以我有以下功能:

function hideValue(value) {
if (this.value == value) {
this.value = '';
}

以及以下表单域:

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

我无法获得隐藏值的功能。当我在函数中 alert(value); 时,它返回正确的值。

我还有一个执行相反操作的 showValue 函数。为什么这些不起作用?

最佳答案

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

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

因此应将函数修改为:

function hideValue(element, value) {
if (element.value == value) {
element.value = '';
}
}

关于Javascript:this.value 函数不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36760616/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com