Reputation: 575
$(document).ready(function() {
$('#switcher-default').bind('click', function() {
$('body').removeClass('narrow');
$('body').removeClass('large');
});
});
the second function:
$(document).ready(function() {
$('#switcher-default').click(function() {
$('body').removeClass('narrow');
$('body').removeClass('large');
});
});
I am a newbie of jQuery, what's the difference between the above code? I feel that add or remove the bind function
, the result is the same.why the code adds the bind event?
Upvotes: 2
Views: 120
Reputation: 16223
It's the same, as you can see on jQuery's documentation regarding .click()
:
This method is a shortcut for .bind('click', handler)
Upvotes: 7
Reputation: 69915
They both will do the same thing attach click
handler to #switcher-default
element. bind
is just other way of attaching any event to matched set of elements.
Using bind
you can attach multiple events with common event handler on the element. The eventType should be separated by a space.
$('#foo').bind('mouseenter mouseleave', function() {
//Do something
});
Upvotes: 2
Reputation: 94499
There is no difference. Both segments of code attach the function to the click event. Bind is just useful if you don't know what type of event you will be binding to.
For example: http://jsfiddle.net/3wCMJ/
Read the Jquery API Documentation: http://api.jquery.com/click/
With regards to the click() function:
This method is a shortcut for .bind('click', handler)
Upvotes: 3
Reputation: 20424
You can find your answer by reading the click()
documentation:
This method is a shortcut for .bind('click', handler) in the first two variations, and .trigger('click') in the third.
And also bind()
documentation suggests using on()
instead of bind()
in version 1.7 and above:
As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements.
Upvotes: 2