简体   繁体   中英

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. I am grabbing 100 new items from an API using ajax and adding them to the current ul by using .append(html) . Each li has a checkbox next to it that when selected needs to call some_function .

The elements that have been rendered are able to access some_function but not the newly loaded ones. How can I access some_function on the newly loaded ajax items? I've never dealt with this before and apparently since the items aren't "rendered" yet they can't access functions?

This is a great situation where you can use the jQuery on() function

You can read more about it here

Use event delegation -

$(document).on('change',".YourInputClass", some_function);

http://api.jquery.com/on/

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.

If <div id="div1"></div> is a dynamically injected element and you want to attach the click event

$('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).on('click', 'input[type="checkbox"]', function(event) {
    // Your code
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM