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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:00:10  来源:igfitidea点击:

Javascript: Setting onclick dynamically and passing in the element itself

javascriptjavascript-events

提问by Nick Van Hoogenstyn

I'm dynamically creating some <div>elements and then filling their innerHTMLproperties with text. I'm trying to set their onclickevent 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 onclickfunction. How would I go about accessing the data of myDivwithin the function being defined for its onclickproperty? myDivwill 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, thiswill refer to the element.

在处理程序内部,this将引用元素。

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

Tadaaa :).

Tadaaa :)。

回答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作为规则