如何将事件绑定到从AJAX请求注入的HTML [英] How to bind events to HTML injected from AJAX requests

查看:104
本文介绍了如何将事件绑定到从AJAX请求注入的HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我通过AJAX请求注入html:

So I am injecting html via an AJAX request:

Ajax响应

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

问题是ID为#my-element的元素来自AJAX请求,但我也需要绑定事件.例如:

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");
    });
 });

显然,上面的事件永远不会触发,因为当页面准备就绪时,尚未从AJAX请求中注入HTML.解决此问题的最佳解决方案是什么?

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?

谢谢.

推荐答案

尝试使用jQuery.on函数: http ://api.jquery.com/on/

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

然后,即使在添加了动态元素的情况下也可以使用.

Then it will work even with dinamically added elements.

这篇关于如何将事件绑定到从AJAX请求注入的HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆