Optimizing some code whose purpose is for better UI
How would you rewrite this? It works, but it has been thrown together. Purpose: If you click anywhere within a td element that contains a checkbox, then the checkbox is selected.
$('td input').filter(':checkbox'开发者_开发百科).each(function() {
$(this).closest('td').addClass('CursorPointer');
});
$('td.CursorPointer').click(function() {
$('input:checkbox',this).click();
});
$('input:checkbox').click(function(myEvent) {
myEvent.stopPropagation();
});
I wonder if this is a good example of adding an event listener, or using the delegate method.
First:
$('td input').filter(':checkbox').each(function() {
$(this).closest('td').addClass('CursorPointer');
});
Is the same as:
$('td').has(':checkbox').addClass('CursorPointer');
Secondly Similar to sdleihssirhc but targeting a specific element (best not to overload document with too many bubbling events).
$('#my-table-id').delegate('.CursorPointer', 'click', function () {
$(':checkbox', this).click();
}).delegate('input:checkbox', 'click', function (e) {
e.stopPropagation();
});
The .click
method in jQuery attaches a click event listener to every single element in the matched group, so yeah, it would probably be a little more efficient if you changed both of those to use event delegation:
$(document).delegate('td.CursorPointer', 'click', function () {
$('input:checkbox', this).click();
}).delegate('input:checkbox', 'click', function (myEvent) {
myEvent.stopPropagation();
});
There's probably a very slightly more efficient way to phrase that in jQuery, but that's the essential idea.
$('td').has(':checkbox').addClass('CursorPointer').click(function(e) {
$('input:checkbox',this).click();
}).find(':checkbox').click(function(e){
e.stopPropagation();
});
Here's a jsfiddle: http://jsfiddle.net/gislikonrad/5G7ee/
精彩评论