jQuery单击不适用于ajax生成的内容 [英] jquery click doesn't work on ajax generated content

查看:48
本文介绍了jQuery单击不适用于ajax生成的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用$(".button").on("click", function(){ });

单击以单击容器上的按钮,然后完成ajax调用并显示内容 会更新新的东西,然后当我尝试单击.button时将无法正常工作……当我单击该按钮时,什么也不会返回.

to click to a button which is on a container but then an ajax call is done and the content gets updated with new stuff and then when i try to click .button it wont work... nothing will get returned when i click the button.

我什至尝试

$(".button").live("click", function(){ });

$(".button").click(function(){ });

我如何使它工作?

我的html:

<div class="container">
   <ul>
       <li>item1</li>
       <li>item2</li>
       <li>item3</li>
   </ul>
   <input type="button" value="reload" class="button" />
</div>

推荐答案

应以这种方式完成.

$('body').on('click', '.button', function (){
        alert('click!');
    });

如果您的容器在ajax请求期间没有更改,则性能更高:

If you have a container that doesn't change during the ajax request, this is more performant:

$('.container').on('click', '.button', function (){
        alert('click!');
    });

始终将委托事件绑定到将包含动态元素的最近的静态元素.

Always bind the delegate event to the closest static element that will contain the dynamic elements.

这篇关于jQuery单击不适用于ajax生成的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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