如何在通过 Ajax 拉入的元素上使用 Jquery document.on()? [英] How to use Jquery document.on() on elements that are pulled in via Ajax?

查看:17
本文介绍了如何在通过 Ajax 拉入的元素上使用 Jquery document.on()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Jquery Mobile shell 页面,我正在使用 Ajax 将表单加载到该页面中.表单有一些复选框,我需要绑定到它们.

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.

奇怪的是,我可以像这样直接在按钮上设置监听器:

Oddly, I can get it to work setting the listener directly on the button like so:

$('input[name="ohneiln"]').on('change', function() {
   alert("hello");
   });

但是当我尝试将侦听器设置为 $(document) 并委托给 checkbox 时,侦听器永远不会触发:

But when I'm trying to set the listener to $(document) and delegate to the checkbox, the listener never fires:

$(document).on('change', 'input[name="ohneiln"]', function() {
   alert("hello");
});

问题:
使用 $(document).on() 为通过 Ajax 加载的动态"元素设置事件绑定的正确方法是什么?这对于 change 事件是不可能的,或者为什么我会遇到麻烦?

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?

感谢您的帮助!

推荐答案

.on() 方法的工作方式会根据您的使用方式而变化.在您的第一个示例中,.on() 方法的行为类似于 bind,并且仅适用于已存在的元素.

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.

第二个示例在许多方面的行为类似于 .live()delegate().并且适用于稍后添加的元素.

The second example behaves like .live() or delegate() in many ways. And will work for elements that are added later.

阅读文档以获得详细说明 http://api.jquery.com/on/

Read the docs for a detailed explanation http://api.jquery.com/on/

这篇关于如何在通过 Ajax 拉入的元素上使用 Jquery document.on()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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