Javascript:动态设置onclick并传入元素本身 [英] Javascript: Setting onclick dynamically and passing in the element itself
问题描述
我正在动态创建一些< div>
元素,然后用文本填充 innerHTML
属性。我正在尝试设置这样的 onclick
事件处理程序:
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:
myDiv.onclick = function() { alert("Hello!") };
我可以做。我想要做的是能够在新定义的 onclick <中访问值/ innerHTML(Javascript和DOM的新内容,所以我不确定我要查找的是什么术语) / code>功能。我如何在为其
onclick
属性定义的函数中访问 myDiv
的数据? myDiv
将简单如下:
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:
<div>StackOverflow</div>
任何帮助都将不胜感激!
Any help would be greatly appreciated!
推荐答案
onclick处理程序在元素的上下文中执行。
The onclick handler is executed in the context of the element.
myDiv.onclick = function () { alert(this.innerHTML); };
这篇关于Javascript:动态设置onclick并传入元素本身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!