javascript events not working with dynamic content added with json

后端 未结 3 1395
别跟我提以往
别跟我提以往 2021-01-20 19:25

I\'m stuck with a situation where my DOM elements are generated dynamically based on $.getJSON and Javascript functions for this elements are not working. I\'ll

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-20 20:01

    Instead of calling on directly on the element, call it on a parent that isn't dynamically added and then use the optional selector parameter to narrow it to the element.

    $('.parent').on('click', '.element', () => {
        // do something
    });
    

    The difference between this and:

    $('.element').on('click', () => {});
    

    is with $('.element').on(), you're only applying the listener to the elements that are currently in that set. If it's added after, it won't be there.

    Applying it to $(.parent), that parent is always there, and will then filter it to all of it's children, regardless when they're added.

提交回复
热议问题