简体   繁体   English

如何使用 javascript 将事件属性添加到 html 标记

[英]How to add event attribute to html tag with javascript

I created some label tag with javascript something like this:我用 javascript 创建了一些 label 标签,如下所示:

 var labelTag = document.createElement("label"); 
 labelTag.id = i; 
 labelTag.className ="myrows"; 
 labelTag.innerHTML = data[1];

It's ok, but i need to add onlick attribute to this label too.没关系,但我也需要在这个 label 中添加 onlick 属性。

So i need to look the result somthing like this:所以我需要看一下这样的结果:

  <label id='0' class='myrows' onclick=myfunction('first','second',..)> some info here</label>

I try with this: labelTag.onclick=myfunction('first',second,...);我试试这个: labelTag.onclick=myfunction('first',second,...);

No code error, but after i run the page on browser and see the source this attibute is missing.没有代码错误,但是在我在浏览器上运行页面并查看源代码后,这个属性就丢失了。 Whats wrong?怎么了?

Thank you,谢谢,

Holian霍利安

This这个

labelTag.onclick = myfunction('first', 'second', ...);

assigns the return value of myfunction to labelTag.onclick .labelTag.onclick返回值分配给myfunction

You have to wrap it into an anonymous function if you want to pass parameters to the function:如果要将参数传递给 function,则必须将其包装到匿名 function 中:

labelTag.onclick = function() {
    myfunction('first', 'second', ...);
};

Note that you won't see any changes in the DOM if you inspect it.请注意,如果您检查它,您将不会看到 DOM 中的任何更改。


For more information about event handling and the various ways to attach handlers, I recommend to read the excellent articles on quirksmode.org .有关事件处理和附加处理程序的各种方法的更多信息,我建议阅读quirksmode.org 上的优秀文章

var labelTag = document.createElement("label"); 
labelTag.id = i; 
labelTag.className ="myrows"; 
labelTag.innerHTML = data[1];
labelTag.onclick = function() {
   alert('Clicked');
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM