Onclick = "func ()" or .click ()?

I was wondering which of the above methods is preferred or is the general guideline that you use $ (elem) .click () for simple things and <a onclick = "func (1, 2, 3, 4);" > when do you need to pass parameters to a script when an element is clicked? I'm trying to use only $ (elem) .click () so that the code is clean and simple, but when you need to pass more than one parameter, it becomes complicated, and calling the onclick = "function seems to be the best solution.

+6
jquery
source share
6 answers

One of the main ideas of jQuery is unobtrusive javascript (i.e. HTML and javascript are two great flavors that don't mix very well). Using a jQuery object and selectors to attach functions is what they would rather do.

+7
source share
$(elem).click(function() { func(1,2,3,4); }); 

It looks like what you want, no?

+5
source share

If parameters can be defined at the moment of click, I would suggest a binding method:

 $('a').click(function(){ someFunc(this.val, 2, 3, 4); }) 

In one case, I might think about doing this inline if you create multiple links in a loop where parameters 1, 2, 3, or 4 change depending on the backend variable or something:

 <% for( int i = 0; i < 4; i++) { %> <a onclick="someFunc(1,<%= i %>,3,4"></a> <% } %> 

Personally, I always try to bind to an event in the $ (document) .ready () callback.

Hope this helps

+4
source share

I prefer to use $ (elem) .click () to support HTML without javascript, I find it cleaner.

+3
source share

I would go with click() , if you have additional parameters that you want to pass to the function, add them to any of the attributes of the object, I usually use rel as follows:

 <a href="#" class="link" rel="parameter1, parameter2, etc">Link</a> 

in a script you can do this:

 $('.link').click(function() { var parameters = $(this).attr('rel').split(','); // Do something return false; }) 
+2
source share

You can pass function parameters when using jQuery:

 $(".selector").click(function() { func(1,"2", someVar); }); 

I prefer to always use jQuery to handle events. I don’t like introducing any behavior into my HTML, even with onclick and related events.

Also, if you programmatically click something with $(".selector").click() , and you have a handler attached using both onclick and jQuery, it will call the jQuery handler first, and then the handler defined using the attribute. But if you click with the mouse, it's the other way around. This can be unexpected and ultimately gives you headaches on the road.

0
source share

All Articles