What is a proper way to add listeners to new elements after using AJAX to get the html content? (jQuery, Javascript)

前端 未结 5 818
谎友^
谎友^ 2021-01-05 09:13

I am making something that can loads new setting pages via AJAX, I am not sure what\'s the most efficient way to bind listeners to those elements from the new content page?<

5条回答
  •  情歌与酒
    2021-01-05 09:32

    I'm not entirely sure what you're asking here, but you can use jQuery's .on() function to bind to elements that already exist in your document, OR elements that will exist in the future.

    Here's a quick example:

    $(document).ready(function () {
        $(document).on('click', '#new-button', function() {
            alert("You clicked the new button");
        });
    
        //get some HTML via ajax. Let's assume you're getting 
        $.get('url', function(res) {
            $('body').append(res);
        });
    });
    

提交回复
热议问题