JQuery $ ('body'). on ('click') always requires .off ('click') to avoid triggering the event multiple times

I have a page on which I list the members of my team (show_crew.php). The page works with an endless scroll plugin, such as Google images. First I show 10 entries. If the user reaches the bottom of show_crew.php, the new "show_crew.php" is added to the old one, showing the next 10 entries.

I carry some jQuery functions built into show_crew.php where I bind events through

$('body').on('click', 'myButton[rel=<? echo $user['id'] ?>]', function() { console.log('foo'); })​ 

Now that show_crew.php is added several times, the event is also bound to the same button several times. I can solve this problem through $('body').off('click', 'myButton') EVERY TIME.

It looks ugly. Is there a more elegant way?

thank you matte

+4
source share
1 answer

You only need to bind delegated events once. Do not reinstall each time you download content.

Using the format $('body').on('click', '...selector...', function () {...}) will pass the event handler to the <body> element. This means that the body will catch all click events and check whether they occurred in the element that matches ...selector... If this happens, it will call the event handler, as if it were running on the matched element.

After you have added the delegate listener, there is no need to worry about cancellation, since the children from <body> can change, and the delegate will be saved for new elements. This is a very good thing and trade .

+18
source

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


All Articles