How to bind events to HTML injected from AJAX requ

2020-03-26 07:27发布

So I am injecting html via an AJAX request:

Ajax Response

  <div id="my-element">HTML from AJAX request</div>

The problem is that the element with id #my-element comes in from the AJAX request, but I need to bind events too it. For example:

 $(document).ready(function() {
    $("#my-element").click(function() {
        alert("hit");
    });
 });

Obviously the event above never fires, because when the page is ready, the HTML has not been injected from the AJAX request yet. What is the best solution to fix this?

Thanks.

4条回答
▲ chillily
2楼-- · 2020-03-26 07:41

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

查看更多
相关推荐>>
3楼-- · 2020-03-26 07:42

Use the on method to make it live.

$(function(){
    $("#my-element").on("click",function() {
        alert("hit");
    });
});
查看更多
欢心
4楼-- · 2020-03-26 07:48

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?

查看更多
ら.Afraid
5楼-- · 2020-03-26 07: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.

查看更多
登录 后发表回答