Javascript: Setting onclick dynamically and passing in the element itself

匿名 (未验证) 提交于 2019-12-03 08:36:05

问题:

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!") };

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!

回答1:

The onclick handler is executed in the context of the element.

myDiv.onclick = function () { alert(this.innerHTML); };


回答2:

Inside the handler, this will refer to the element.

myDiv.onclick = function() { alert(this.innerHTML) };

Tadaaa :).



回答3:

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



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!