如何在通过 Ajax 拉入的元素上使用 Jquery document.on()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10864683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use Jquery document.on() on elements that are pulled in via Ajax?
提问by frequent
I have a Jquery Mobile shell page, which I'm loading a form into using Ajax. The form has some checkboxes, which I need to bind to.
我有一个 Jquery Mobile shell 页面,我正在使用 Ajax 加载一个表单。表单有一些复选框,我需要绑定到它们。
Oddly, I can get it to work setting the listener directly on the button like so:
奇怪的是,我可以让它直接在按钮上设置侦听器,如下所示:
$('input[name="ohneiln"]').on('change', function() {
alert("hello");
});
But when I'm trying to set the listener to $(document)
and delegate to the checkbox
, the listener never fires:
但是当我尝试将侦听器设置为$(document)
并委托给 时checkbox
,侦听器永远不会触发:
$(document).on('change', 'input[name="ohneiln"]', function() {
alert("hello");
});
Question:
What is the correct way to set an event binding for "dynamic" elements being loaded in via Ajax using $(document).on()
? Is this not possible for change
events or why am I running into troubles?
问题:
为使用 Ajax 加载的“动态”元素设置事件绑定的正确方法是什么$(document).on()
?这对change
事件来说是不可能的,还是为什么我会遇到麻烦?
Thanks for help!
感谢帮助!
采纳答案by codaniel
The way the .on()
method works changes according to how you use it. In your first example the .on()
method behaves similar to bind
and will only work on elements that already exist.
该方法的.on()
工作方式根据您使用它的方式而变化。在您的第一个示例中,该.on()
方法的行为类似于bind
并且仅适用于已存在的元素。
The second example behaves like .live()
or delegate()
in many ways. And will work for elements that are added later.
第二个例子表现得像.live()
或delegate()
在很多方面。并将适用于稍后添加的元素。
Read the docs for a detailed explanation http://api.jquery.com/on/
阅读文档以获取详细说明http://api.jquery.com/on/