jQuery should i group selectors with similar events as 1 selector.
I always find myself having multpile selectors with click events in many areas of the code. Is there any downside to having it done this way.
ex:
$('#id').live('click'....)
$('div').live('click'....)
$('.class p').live('click'..)
or is it better to have all combined in one selector such as
$('#id, div, .class p')..
Sometimes i find it difficult combining all on one selector as i have to know which 开发者_如何转开发item was clicked. Not all items have id's. some have id's some classes and some are just plain html tags. If combining all in one selector is better, how can i tell which of the item where clicked.
If you need to differentiate between items during the click event - thus, the behaviour for every clicked element should differ, you should bind an event for every element.
If the elements can be grouped together because they share the same behaviour, there really is no reason not to group the selectors.
When binding a click event to multiple elements, $(this)
always refers to the clicked element, which allows you to do some element-specific routines if you'd like. For example:
HTML:
<ul>
<li>Some item</li>
<li>Another one</li>
<li>And another one</li>
</ul>
<span>Wee</span>
JavaScript:
$(function() {
$('span, li').click(function() {
$(this).append($('<div>Child div added to clicked element</div>'));
});
});
Example:
http://jsfiddle.net/ArondeParon/db8K3/
If they all have the same click logic, I'd combine their selectors to keep the code verbosity down. If you'd like to tell which item was clicked, you can do so by accessing the event's target
property. The target
property has greater granularity than the this
reference.
You can use
$(this).attr('id')
to find the id of the clicked element. Fine to use one selector if you are doing generally the same thing, otherwise probably cleaner to separate it out.
精彩评论