开发者

How to add event attribute to html tag with JavaScript

开发者 https://www.devze.com 2023-03-03 07:14 出处:网络
I created some label tag with JavaScript something like this: var labelTag = document.createElement("label");

I created some label tag with JavaScript something like this:

 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 开发者_如何学JAVAlabel too.

So I need to look the result something like this:

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

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

No code error, but after I run the page on browser and see the source this attribute is missing. What's wrong?


This

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

assigns the return value of myfunction to labelTag.onclick.

You have to wrap it into an anonymous function if you want to pass parameters to the function:

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

Note that you won't see any changes in the DOM if you inspect it.


For more information about event handling and the various ways to attach handlers, I recommend to read the excellent articles on quirksmode.org.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号