Click event for dynamically created list items using jquery

I have a dynamically generated list, and then I click on an element and pass index() another function.

The problem is that this list populates dynamically and my code does not respond when I make a click event. BUT, if I add some Static li elements to the list in addition to dynamically populated those that work Static. It is very strange.

Some codes:

This dynamically creates a list:

 function SetOpenRecentURL( openRecentURL ) { $('#recentProjectsId').append('<li>' + openRecentURL + '</li>') } 

This is a click event to pass Index ():

 $('#recentProjectsId li').on('click', function () { var projIndex = $(this).index(); console.log(projIndex) OpenProject() }) 

HTML with multiple static faces

 <div class="recentProjects" id="recentProjectsId"> <li>Test 1</li> <li>Test 2</li> </div> 

When I run my program, my list looks perfect and includes whether my static plus my dynamic ones, but I can’t click on dynamic ones, only static ones.

+6
source share
2 answers

When I run my program, my list looks perfect and includes whether my static plus my dynamic ones, but I can’t click on dynamic ones, only static ones.

This is because your code binds the click handler, it is only bound to elements on the page at the time the listener is bound. Configure the click listener a little differently and it will work using event delegation:

 $('#recentProjectsId').on('click', 'li', function () { // snip... }); 

By .on() an additional selector argument .on() :

A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event always fires when it reaches the selected item.


Please note that your HTML is not valid. <li> elements are valid only within <ul> s, <ol> s and <menu> s.

+17
source

You can use delegated events :

 $("#recentProjectsId").on("click", "li", function() { var projIndex = $(this).index(); console.log(projIndex) OpenProject() }); 

Here #recentProjectsId is the parent <li> element.

0
source

All Articles