javascript events not working with dynamic content added with json

后端 未结 3 1393
别跟我提以往
别跟我提以往 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: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);
        });
    });    
    

提交回复
热议问题