How to bind events to HTML injected from AJAX requests

前端 未结 4 857
逝去的感伤
逝去的感伤 2021-01-14 20:48

So I am injecting html via an AJAX request:

Ajax Response

  
HTML from AJAX request
相关标签:
4条回答
  • 2021-01-14 20:55

    Try to use jQuery.on function: http://api.jquery.com/on/

    $(document).on('click', '#my-element', function () { ... });
    

    Then it will work even with dinamically added elements.

    0 讨论(0)
  • 2021-01-14 21:12

    Add your event after injecting html via an AJAX request has been completed
    or
    you can use on method

    see this example also

    Event binding on dynamically created elements?

    0 讨论(0)
  • 2021-01-14 21:16

    Use the on method to make it live.

    $(function(){
        $("#my-element").on("click",function() {
            alert("hit");
        });
    });
    
    0 讨论(0)
  • 2021-01-14 21:16

    Do the binding in the success callback of your ajax call, after you ahve inserted the html into the DOM.

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