javascript events not working with dynamic content added with json

后端 未结 3 1391
别跟我提以往
别跟我提以往 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.

    0 讨论(0)
  • 2021-01-20 20:03

    Firstly you need to use a delegated event handler to catch events on dynamically appended elements. Then you can call the .slider() method again within the success handler function to instantiate the plugin on the newly appended content. Try this:

    $(document).ready(function(){
        $('#parentElement').on('click', '.element', function() {
            $(this).toggleClass('active');
        });
    
        var sliderOptions = { /* slider options here */ };
        $(".slider").slider(sliderOptions);
    
        $.getJSON('json/questions.json', function(data) {
            // generating some DOM elements...
            $('#parentElement .slider').slider(sliderOptions);
        });
    });    
    
    0 讨论(0)
  • 2021-01-20 20:14

    the easiest way is to add this after you add/generate your DOM

    $('script[src="site.js"]').remove();
    $('head').append('<script src="site.js"></script>');
    

    of course your js function that generates DOM needs to be on another file than your site.js

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