JQuery create element fires onclick event

I am creating a binding using jQuery and the onclick event seems to fire when the element is created. I used this method to create elements several times with this project without problems, do I have the wrong end of the stick?

jQuery('<a/>', { href: '#', name: 'link_html_edit', id: 'link_html_edit', html: 'input HTML text', onclick: alert('test') }).appendTo(spanDefaultValue); 

thanks

+4
source share
3 answers

You call alert('test'); and assign it the return value of onclick . Use this instead:

 onclick: function(){ alert('test'); } 

Since I'm sure alert('test') is just an example, I should also point out that if you have the same problem with some function, you can probably just change your code:

 onclick: somefunction() 

To:

 onclick: somefunction 

You only need to wrap it in an anonymous function the way I did with alert('test'); if you pass arguments to a function other than the event object, which is usually passed to the event handler.

+6
source

By looking at the jQuery documentation on this page, you should do the following:

 $("<a/>", { href: '#', name: 'link_html_edit', id: 'link_html_edit', html: 'input HTML text', click: function(){ alert('test'); } }).appendTo("body"); 
+6
source

This is a much better alternative.

 $("<a/>", { href: '#', name: 'link_html_edit', id: 'link_html_edit', html: 'input HTML text' }).bind('click',function(){ // your function}).appendTo("body"); 
+4
source

All Articles