Javascript:动态设置 onclick 并传入元素本身
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8181684/
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
Javascript: Setting onclick dynamically and passing in the element itself
提问by Nick Van Hoogenstyn
I'm dynamically creating some <div>
elements and then filling their innerHTML
properties with text. I'm trying to set their onclick
event handlers like this:
我正在动态创建一些<div>
元素,然后innerHTML
用文本填充它们的属性。我正在尝试onclick
像这样设置他们的事件处理程序:
myDiv.onclick = function() { alert("Hello!") };
That I can do. What I would like to do is be able to access the value / innerHTML (new to Javascript and DOM, so I'm unsure of what term is what I'm looking for) within the newly defined onclick
function. How would I go about accessing the data of myDiv
within the function being defined for its onclick
property? myDiv
will be something simple like:
我能做到的。我想要做的是能够在新定义的onclick
函数中访问值/innerHTML(Javascript 和 DOM 的新手,所以我不确定我正在寻找什么术语)。我将如何访问myDiv
为其onclick
属性定义的函数内的数据?myDiv
将是一些简单的东西:
<div>StackOverflow</div>
Any help would be greatly appreciated!
任何帮助将不胜感激!
回答by J. K.
The onclick handler is executed in the context of the element.
onclick 处理程序在元素的上下文中执行。
myDiv.onclick = function () { alert(this.innerHTML); };
回答by Matt
Inside the handler, this
will refer to the element.
在处理程序内部,this
将引用元素。
myDiv.onclick = function() { alert(this.innerHTML) };
回答by Mike Sav
I think what you're after is:
我认为你所追求的是:
myDiv.onclick = function () {
alert(this.innerHTML);
};
Personally I'd stay away from innerText (due to browser issues) and use innerHTML as a rule
我个人会远离innerText(由于浏览器问题)并使用innerHTML作为规则