⊗jqEvtDe 100 of 113 menu

Delegation in jQuery

If you've studied JavaScript, you've already encountered the topic of event delegation, which can, for example, help you avoid problems when assigning events to new elements. Let's see how this would look for jQuery.

Let's take the following HTML code:

<ul> <li>text</li> <li>text</li> <li>text</li> </ul>

CSS for him it looks like this:

li { width: 100px; cursor: pointer; }

Now, using the on method, let's bind the click method not to the list item li, as we did in the previous lessons, but to the list itself ul. We will also pass the second (optional) parameter 'li' as a descendant selector. Let's see what we got:

$('ul').on('click', 'li', function() { $(this).append('!'); });

Given ul, it contains several li. Make a button under ul, when clicked, a new li with the text 'item' will be added to the end of ul. Make it so that when you click on each li, '!' will be added to its end. This should work for newly added li as well. Solve the problem using delegation (that is, the event should be assigned to ul).

A table with users with two columns: first name and last name is given. Under the table, create a form that will allow adding a new user to the table. Make it so that when you click on any cell, prompt appears, with which you can change the cell text. Solve the problem using delegation (that is, the event should be assigned to table).

byenru