JQuery bind event after adding element dynamic

后端 未结 3 1395
广开言路
广开言路 2021-01-25 00:10

I have an issue after adding a element dynamically it doesn\'t have the click event, so i have the following:

$(\".myclass > li\").click(function () {
    ...         


        
相关标签:
3条回答
  • 2021-01-25 00:55

    need to use event delegation to support dynamic elements

    $(".myclass").on('click', '> li' function () {
        ...
    });
    
    0 讨论(0)
  • 2021-01-25 00:58

    Since the element is added after you bind the event, it doesn't have the handler attached and the bind function doesn't listen for any new elements that might be added.

    Thus, you need to use event delegation. When an event triggers, it will bubble up all the way to the parent document. Using the jQuery .on() function you can listen for events that have bubbled up from their target.

    In your case, you should use the following:

    $(parent).on("click", "li", function() { ... });

    The above will listen for click events that occur on li elements and bubble up to parent. Inside the event handler this will refer to the li element on which the event triggered. In case you don't know the parent, you can listen on document.

    You can learn more about the .on() function here.

    0 讨论(0)
  • 2021-01-25 01:04

    You need to use Event Delegation. You have to use .on() using delegated-events approach.

    i.e.

    $(document).on('event','selector',callback_function)
    

    In your case

    $(document).on('click', '.myclass > li', function () {
        ...
    });
    

    OR if you want to apply to ALL list items:

    $(".myclass").on('click', '> li', function () {
        ...
    });
    
    0 讨论(0)
提交回复
热议问题