简体   繁体   English

为什么通过ajax加载数据后,我的JQuery代码不起作用?

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

I have a tree view with this jquery code : 我有这个jQuery代码树视图:

$(".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 ). 当树状视图被更改然后再用Ajax加载时,它不起作用(我对打开和关闭的子项使用+和-,但是当我单击+或-发生任何事情时)。 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标签代替动态修改的.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. 根据显示的内容,如果要替换 .treeview元素,则不会设置任何处理程序来处理新的替换.treeview元素。

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. 您甚至可以使用$(document.body).on(... ,但是通常有一个不变的容器,它比您要使用的容器更接近。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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