Reputation: 1856
I was wondering which one 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 you need to pass parameters to the script when the element is clicked? I've been trying to only use $(elem).click() to keep the code clean and simple, but when you have to pass more than one parameter it gets tricky and function call on onclick="" seems like a better solution.
Upvotes: 6
Views: 863
Reputation: 86413
I'd go with the click()
as well, if you have additional parameters that you want to pass to the function, add them to any of the object's attributes, I usually use rel
like this:
<a href="#" class="link" rel="parameter1, parameter2, etc">Link</a>
in the script you can do this:
$('.link').click(function() {
var parameters = $(this).attr('rel').split(',');
// Do something
return false;
})
Upvotes: 2
Reputation: 41823
You can pass parameters to a function when you use jQuery:
$(".selector").click(function() { func(1,"2", someVar); });
I prefer to always use jQuery for my event handling. I don't like putting any behavior in my HTML, even with onclick
and related events.
Also, if you programmatically click something using $(".selector").click()
and you have a handler attached using both onclick
and jQuery, it will call the jQuery handler first, then the handler set using the attribute. But if you click with your mouse, it's the other way around. That might be unexpected, and end up giving you headaches down the road.
Upvotes: 0
Reputation: 9136
If the parameters could be determined at the moment of the click, I would suggest the binding method:
$('a').click(function(){ someFunc(this.val, 2, 3, 4); })
One case I could think of of doing it inline, is if you're building multiple links in a loop where params 1, 2, 3 or 4 are varying according to a 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 the event in a $(document).ready() callback.
Hope this helps
Upvotes: 4
Reputation: 39325
One of the main ideas behind jQuery is unobtrusive javascript (i.e. HTML and javascript are two great tastes that don't taste great together). Using the jQuery object and selectors to attach the functions is what they would prefer you do.
Upvotes: 7
Reputation: 66436
I prefer to use $(elem).click() to keep my HTML javascript-free, I consider it cleaner.
Upvotes: 3
Reputation: 38740
$(elem).click(function() {
func(1,2,3,4);
});
That seems like what you want, no?
Upvotes: 5