简体   繁体   中英

Why my JQuery code doesn't work after data loading through ajax?

I have a tree view with this jquery code :

$(".treeView").on("click", ".CollOpen, .CollClosed", function () {
    $(this).toggleClass("CollOpen CollClosed").nextAll('ul').first().toggle();
});

It works correctly when page loaded. When the tree view is changed and then loaded with Ajax , it doesn't work ( i have + and - for opened and closed child , but when i click on + or - anything happend ). If i refresh my page it works correctly again. why ?

could you help me , please ?

Try using the body tag instead of the dynamically modified .treeview :

$("body").on("click", ".CollOpen, .CollClosed", function () {
    $(this).toggleClass("CollOpen CollClosed").nextAll('ul').first().toggle();
});

With what you've shown, if you're replacing the .treeview element, then no handler will be set up to handle the new, replacement .treeview element.

If that's the case, you can just hook the event on the container of the treeview, basically the first element that doesn't get replaced. Eg:

$(".treeview_container_that_stays_put").on("click", ".treeView .CollOpen, .treeView .CollClosed", function () {
    $(this).toggleClass("CollOpen CollClosed").nextAll('ul').first().toggle();
});

You could even use $(document.body).on(... , but usually there's an unchanging container closer to what you're working with than that.

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