如何添加 onclick 事件以在 javascript 中创建新元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6156159/
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-23 20:28:22  来源:igfitidea点击:

how to add onclick event to create new element in javascript

javascript

提问by thuk

I have created a labelelement. I need to add onclickevent to that...

我创建了一个label元素。我需要添加onclick事件...

function a(me) {
    var d=document.createElement("label");
    d.id=me.id;
    d.onClick="a(10)";
    d.innerHTML="welcome";
    document.body.appendChild(d);
}

HTML:

HTML:

<label id="1" onclick="a(this)">aa</label>
<label id="2" onclick="a(this)">bb</label>
<label id="3" onclick="a(this)">aa</label>

actually what happens is when i click the any of three labels in html. another label is created and displays welcome. now when i click the newly created label "welcome" it does not display anything...... that is the onclick event added to newly created label is not working ....... any suggestion.................

实际上,当我单击 html 中的三个标签中的任何一个时,会发生什么。另一个标签被创建并显示欢迎。现在,当我单击新创建的标签“欢迎”时,它不显示任何内容......那是添加到新创建标签的 onclick 事件不起作用......任何建议...... …………

回答by maerics

You need to set d.onclick=function(){a(1);};, note that the case matters here (not "onClick").

您需要设置d.onclick=function(){a(1);};,请注意这里的大小写很重要(不是“onClick”)。

[Edit]

[编辑]

Based on your comments and updated questions I've created a jsFiddle to demonstratehow you might turn your code into something that works.

根据您的评论和更新的问题,我创建了一个jsFiddle 来演示如何将代码转换为有效的内容。

回答by Senad Me?kin

d.setAttribute('onclick', 'alert(\'hello\');');

回答by Juan David Castro

For creating an attribute to a HTML tag, sometimes we have to add this:

要为 HTML 标记创建属性,有时我们必须添加以下内容:

yourTag.src
yourTag.src = 'http://lolxd.com/404.png'

But there are special attributes, and them have diferents ways for editing:

但是有一些特殊的属性,它们有不同的编辑方式:

yourTag.classList
yourTag.className

And there is the onclickattribute, wichwe can use it like this:

还有一个onclick属性,我们可以这样使用它:

// The first way
obj.onclick = function () { alert('lalala') }
// With the Event Listener
obj.addEventListener('click', function () { alert('lalala') }, false)
// Or, a text-render way
obj.setAttribute('onclick', 'alert(`lalala`)')

I recomend you the Event Listener way, but try all :D

我向你推荐事件监听器的方式,但尝试所有:D