0

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 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?

1
  • can we try with jQuery?? Commented May 4, 2011 at 10:30

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

ehh...i tought it shown in the source, your comment is work well too, but that was the second one..so...thank you Master
@holian: i tought it shown in the source I don't know that you mean with that. that was the second one And what do you mean with that?
1
var labelTag = document.createElement("label"); 
labelTag.id = i; 
labelTag.className ="myrows"; 
labelTag.innerHTML = data[1];
labelTag.onclick = function() {
   alert('Clicked');
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.