Javascript 当前元素作为其事件函数参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4268085/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:39:35  来源:igfitidea点击:

The current element as its Event function param

javascriptdom

提问by Florian Müller

I've got an element

我有一个元素

<input type="text">

On this, there is an Event

在此,有一个事件

onChange="myfunction(param)".

"param" is the content of the input itself. How can I handle, that, when I fire onChange (so complete the change of the field), in this param is the actual value of this field?

“param”是输入本身的内容。我该如何处理,当我触发 onChange(因此完成字段的更改)时,此参数中是此字段的实际值?

Is it possible to do something like that:

是否有可能做这样的事情:

onChange="myfunction(document.getElementById('this_id'))"

回答by hunter

You can pass thisto myFunctionwhich will be the input

您可以传递thismyFunctionwhich 将是input

<input type="text" onChange="myfunction(this)" />

then myFunctioncould look like this:

然后myFunction看起来像这样:

function myFunction(obj)
{
    var value = obj.value; // the value of the textbox
}

回答by SLaks

Inside an inline event handler, thiswill refer to the DOM element.

在内联事件处理程序中,this将引用 DOM 元素。

Therefore, you can write onchange="myfunction(this)"to pass the DOM element itself to the function.

因此,您可以编写onchange="myfunction(this)"将 DOM 元素本身传递给函数。

回答by Nick Craver

To get the .valueinline, it would look like this:

要获得.value内联,它看起来像这样:

<input type="text" onchange="myfunction(this.value)" />