用jQuery附加选择,委托/事件不起作用 [英] Appended select with jQuery, delegate/on event not working

查看:127
本文介绍了用jQuery附加选择,委托/事件不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.quantity选择更改时,我想创建一个事件侦听器.

I would like to make a event listener, for when .quantity select changes.

由于live()已贬值,因此我尝试了两者:

Since live() is depreciated, I've tried the both:

$('.variant').delegate('.quantity', 'change', function()

http://jsfiddle.net/PdA4W/

$('.variant').on('change', '.quantity', function()

http://jsfiddle.net/PdA4W/2/

问题是,当您单击添加"(它已克隆并附加了一个变体div)时,事件侦听器不会侦听内部选择内容的更改.没有警报.

The problem is, that when you click Add (and it has cloned and appended a variant div), that the event listener doesnt listen at the change on the select thats inside. No alert.

仅适用于第一个选择

这里可能是什么问题?

推荐答案

尝试以下方法:

$(document).on('change', '.variant', function(){
    alert(1);
});

DOM并不真正意识到您是动态添加元素的.使用上面的代码,它几乎忽略了该事件,并将事件绑定到选择器指示的所有将来元素. http://jsfiddle.net/hescano/PdA4W/3/

The DOM is not really aware that you added elements dynamically. With the code above, it pretty much ignores that, and binds the event to all the future elements indicated by your selector. http://jsfiddle.net/hescano/PdA4W/3/

从JQuery文档中: http://api.jquery.com/on/

From JQuery documentation: http://api.jquery.com/on/

事件处理程序仅绑定到当前选定的元素;他们 在您的代码调用 .on()时页面上必须存在该字符. 为了确保元素存在并可以选择,请执行事件 在文档就绪处理程序内绑定元素中的元素 页面上的HTML标记.如果要在页面中注入新的HTML, 选择元素并在新的HTML是后附加事件处理程序 放置到页面中.或者,使用委托事件来附加事件 处理程序,如下所述.

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next.

因此,您可以在每次单击链接后重新绑定事件,或按照上面的代码进行操作.

So you can either re-bind the event after every time you click the link, or do it as in the code above.

这篇关于用jQuery附加选择,委托/事件不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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