Click event on dynamically generated list items using jquery

前端 未结 2 422
失恋的感觉
失恋的感觉 2020-12-03 12:33

I have a list being dynamically generated and then I click on the item and pass the index() to another function.

The problem is that this list is being

相关标签:
2条回答
  • 2020-12-03 13:12

    When I run my program my list looks perfect and includes my static li plus my dynamic ones, but I cannot click on the dynamic ones, only static.

    That's because, the way your code binds the click handler, it is only bound to elements in the page at the time that the the listener is bound. Set up the click listener just a little differently and it will work, by taking advantage of event delegation:

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

    By specifying an additional selector argument to .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 is always triggered when it reaches the selected element.


    Note that your HTML is currently invalid. <li> elements are only valid inside of <ul>s, <ol>s, and <menu>s.

    0 讨论(0)
  • 2020-12-03 13:30

    You may use delegated events:

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

    Here #recentProjectsId is the parent element of <li>.

    0 讨论(0)
提交回复
热议问题