简体   繁体   中英

How to add event attribute to html tag with javascript

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 label too.

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,...);

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 .

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');
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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