在 JavaScript 中为新添加的元素添加 onclick 事件

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

Add onclick event to newly added element in JavaScript

javascripteventsnew-operatorelementadd

提问by SolidSnake

I have been trying to add onclick event to new elements I added with JavaScript.

我一直在尝试将 onclick 事件添加到我用 JavaScript 添加的新元素中。

The problem is when I check document.body.innerHTML I can actually see the onclick=alert('blah') is added to the new element.

问题是当我检查 document.body.innerHTML 时,我实际上可以看到 onclick=alert('blah') 被添加到新元素中。

But when I click that element I don't see the alert box is working. In fact anything related to JavaScript is not working..

但是当我单击该元素时,我没有看到警报框在工作。事实上,任何与 JavaScript 相关的东西都不起作用。

here is what I use to add new element:

这是我用来添加新元素的内容:

function add_img() { 
  var elemm = document.createElement('rvml:image'); 
  elemm.src = 'blah.png';
  elemm.className = 'rvml';
  elemm.onclick = "alert('blah')";
  document.body.appendChild(elemm);
  elemm.id = "gogo";
  elemm.style.position='absolute';
  elemm.style.width=55;
  elemm.style.height=55;
  elemm.style.top=200;
  elemm.style.left=300;
  elemm.style.rotation=200; 
}

Here is how I call this function:

这是我调用此函数的方式:

<button onclick=add_img()>add image</button>

Now the image draws perfectly inside the browser. But when I click the image I don't get that alert.

现在图像在浏览器中完美绘制。但是当我单击图像时,我没有收到该警报。

回答by kennytm

.onclickshould be set to a function instead of a string. Try

.onclick应该设置为函数而不是字符串。尝试

elemm.onclick = function() { alert('blah'); };

instead.

反而。

回答by Boris Delormas

Not sure but try :

不确定,但尝试:

elemm.addEventListener('click', function(){ alert('blah');}, false);

回答by bonafernando

You can also set attribute:

您还可以设置属性:

elem.setAttribute("onclick","alert('blah');");

回答by MinhNguyen

you can't assign an event by string. Use that:

您不能按字符串分配事件。使用那个:

elemm.onclick = function(){ alert('blah'); };

回答by dxh

Short answer: you want to set the handler to a function:

简短回答:您想将处理程序设置为函数:

elemm.onclick = function() { alert('blah'); };

Slightly longer answer: you'll have to write a few more lines of code to get that to work consistently across browsers.

稍微长一点的答案:你必须多写几行代码才能让它在浏览器中一致地工作。

The fact is that even the sligthly-longer-code that might solve that particular problem across a set of common browsers will still come with problems of its own. So if you don't care about cross-browser support, go with the totally short one. If you care about it and absolutely only want to get this one single thing working, go with a combination of addEventListenerand attachEvent. If you want to be able to extensively create objects and add and remove event listeners throughout your code, and want that to work across browsers, you definitely want to delegate that responsibility to a library such as jQuery.

事实是,即使可能在一组常见浏览器中解决特定问题的稍长代码仍然会带来其自身的问题。因此,如果您不关心跨浏览器支持,请选择完全简短的支持。如果您关心它并且绝对只想让这件事起作用,请结合使用addEventListenerattachEvent。如果您希望能够在整个代码中广泛地创建对象并添加和删除事件侦听器,并希望它跨浏览器工作,那么您肯定希望将该责任委托给一个库,例如 jQuery。

回答by Guillaume Lebourgeois

I don't think you can do that this way. You should use :

我不认为你可以这样做。你应该使用:

void addEventListener( 
  in DOMString type, 
  in EventListener listener, 
  in boolean useCapture 
); 

Documentation right here.

文档就在这里

回答by crazy2be

You have three different problems. First of all, values in HTML tags should be quoted! Not doing this can confuse the browser, and may cause some troubles (although it is likely not the case here). Second, you should actually assign a function to the onclick variable, as someone else meantioned. Not only is this the proper way to do it going forward, but it makes things much simpler if you are trying to use local variables in the onclick function. Finally, you can try either addEventListener or jQuery, jQuery has the advantage of a nicer interface.

你有三个不同的问题。首先,HTML 标签中的值应该被引用!不这样做会混淆浏览器,并可能导致一些麻烦(尽管这里可能不是这种情况)。其次,您应该像其他人所说的那样,为 onclick 变量分配一个函数。这不仅是前进的正确方法,而且如果您尝试在 onclick 函数中使用局部变量,它会使事情变得更简单。最后,您可以尝试 addEventListener 或 jQuery,jQuery 的优点是界面更好。

Oh, and make sure your HTML validates! That could be an issue.

哦,并确保您的 HTML 验证!那可能是个问题。

回答by bresleveloper

cant say why, but the es5/6 syntax doesnt work

不能说为什么,但 es5/6 语法不起作用

elem.onclick = (ev) => {console.log(this);}not working

elem.onclick = (ev) => {console.log(this);}不工作

elem.onclick = function(ev) {console.log(this);}working

elem.onclick = function(ev) {console.log(this);}在职的

回答by Alex

JQuery:

查询:

elemm.attr("onclick", "yourFunction(this)");

or:

或者:

elemm.attr("onclick", "alert('Hi!')");

回答by Prateek

In case you do not want to write all the code you have once written in the function you called. Please use the following code, using jQuery:

如果您不想在您调用的函数中编写您曾经编写的所有代码。请使用以下代码,使用 jQuery:

$(element).on('click', function () { add_img(); });

$(element).on('click', function () { add_img(); });