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
The current element as its Event function param
提问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 this
to myFunction
which will be the input
您可以传递this
给myFunction
which 将是input
<input type="text" onChange="myfunction(this)" />
then myFunction
could look like this:
然后myFunction
看起来像这样:
function myFunction(obj)
{
var value = obj.value; // the value of the textbox
}
回答by SLaks
Inside an inline event handler, this
will 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 元素本身传递给函数。