[英]jquery how to access events on html that was inserted to the DOM
In my web app I have an unordered list of 15 items that appear on load. 在我的Web应用程序中,有15个项目的无序列表,这些列表在加载时显示。 I am grabbing 100 new items from an API using ajax and adding them to the current
ul
by using .append(html)
. 我正在使用ajax从API捕获100个新项目,并使用
.append(html)
将它们添加到当前ul
。 Each li
has a checkbox next to it that when selected needs to call some_function
. 每个
li
旁边都有一个复选框,选中该复选框时需要调用some_function
。
The elements that have been rendered are able to access some_function
but not the newly loaded ones. 已渲染的元素能够访问
some_function
但不能访问新加载的元素。 How can I access some_function
on the newly loaded ajax items? 如何访问新加载的ajax项目上的
some_function
? I've never dealt with this before and apparently since the items aren't "rendered" yet they can't access functions? 我以前从未处理过这个问题,显然因为这些项目不是“呈现”的,但它们无法访问功能?
Use event delegation - 使用事件委托-
$(document).on('change',".YourInputClass", some_function);
You should use event delegation for such scenarios.. Basically you bind the handler to the parent element and filter out by a selector to trigger the handler. 在这种情况下,您应该使用事件委托。.基本上,您将处理程序绑定到父元素,并由选择器过滤出来以触发处理程序。
Below is the pseudo code, 下面是伪代码,
$('ul').on('click', '.checkbox', function () {
some_function.call(this); //maintain the context if it is an external function.
});
You need to delegate the events.
您需要
delegate the events.
If <div id="div1"></div>
is a dynamically injected element and you want to attach the click event 如果
<div id="div1"></div>
是动态注入的元素,并且您想附加click事件
$('staticContainer').on('click', '#div1', some_function);
Without seeing your code I am guessing that you have bound an event handler directly to the checkboxes 没有看到您的代码,我想您已经将事件处理程序直接绑定到了复选框
$('input[type="checkbox"]').click(function(event) {
// Your code
});
To make this work with content added after the handler was created you would need to use a delegated handler that binds to a lower level, unchanged element and bubbles an event up to the checkboxes. 要使此功能与创建处理程序后添加的内容一起使用,您将需要使用委派的处理程序,该处理程序绑定到较低级别的,未更改的元素,并将事件冒泡到复选框。 I have used
document
though it would be advisable to bind it to a dom node further up, most likely the ul
that the checkboxes are added to. 我使用过
document
尽管建议将其绑定到更远的dom节点,最有可能是将复选框添加到的ul
。
$(document).on('click', 'input[type="checkbox"]', function(event) {
// Your code
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.