JQuery should group selectors with similar events as 1 selector.

I always find that I have multigrid selectors with click events in many areas of code. Is there a drawback to doing so?

Example:

$('#id').live('click'....)
$('div').live('click'....)
$('.class p').live('click'..)

or better, that all be combined into one selector, for example

$('#id, div, .class p')..

Sometimes it’s difficult for me to combine everything on one selector, because I need to know which element was pressed. Not all elements have identifiers. some of them have some classes, and some are just html tags. If it's best to combine everything in one selector, how can I determine which of the elements clicked.

+3
source share
3 answers

- , , .

, , .

click , $(this) clicked, , . :

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>'));
    });
});

:

http://jsfiddle.net/ArondeParon/db8K3/

+3

, , . , , , target property. target , this.

+1

you can use

$(this).attr('id')

to find the clicked element id. It is great to use a single selector if you are doing the same in general, otherwise it might be cleaner to separate it.

0
source

Source: https://habr.com/ru/post/1794882/


All Articles