How to dynamically rebind JQuery Objects

前端 未结 2 1634
遇见更好的自我
遇见更好的自我 2021-01-19 23:28

I am making a module for the Joomla! page of a client that uses Ajax to render different queries to the database. The result of these queries is that I regenerate the entire

相关标签:
2条回答
  • 2021-01-19 23:48

    Bind the event handler on a parent element and use event delegation to handle the events. By binding the event handler on a parent element you don't need to bind it on all the child elements.

    /HTML/

    <div id="container">
        <button id="button1" class="click">button with click</button>
        <button id="button2" class="click">button with click</button>
    </div>
    

    /Javascript/

    // use this
    $("#container").on("click", ".click", function(){
        alert(this.id + ": I've been clicked.");
    });
    
    // don't use this
    $(".click").on("click", function(){
        alert(this.id + ": I've been clicked.");
    });
    
    0 讨论(0)
  • 2021-01-19 23:56

    You hinted at the right plan: use .on(). Remember though that when you're delegating a listener, you need to delegate to a listener that will not be destroyed.

    Or in other words:

    // will not do anything useful for this scenario:
    $('.something').on('click', function() { /* ... */ });
    

    is different from

    // use the document as a listener: will work but not efficient
    $(document).on('click', '.something', function() { /* ... */ });
    

    which is different from

    // use a closer ancestor that is NOT destroyed. Best option if you can
    $('#someAncestor').on('click', '.something', function() { /* ... */ });
    
    0 讨论(0)
提交回复
热议问题