我在显示 MySQL 查询的 while 循环中创建了 div。我想用 .slideToggle 隐藏和显示它们。我不能使用一个类,因为那样会触发页面上的每个特定 div 向下滑动。
我认为这会在 while 循环中重复并找到最接近的 toggleSectionDyn div id。显然不是。
<div class="actions"><a href="#" id="toggleButtonDyn">Add</a></div>
<div id="toggleSectionDyn">Some content</div>
<script>
$("#toggleButtonDyn").click(function(){
$(this).closest("#toggleSectionDyn").slideToggle("slow");
return false;
});
</script>
最佳答案
编辑:live 已弃用。考虑使用 .on()
您想使用 .live()
$("#toggleButtonDyn").live('click', (function(){
$(this).closest("#toggleSectionDyn").slideToggle("slow");
return false;
});
来自 .live()接口(interface)
The .live() method is able to affect elements that have not yet been added to the DOM through the use of event delegation: a handler bound to an ancestor element is responsible for events that are triggered on its descendants. The handler passed to .live() is never bound to an element; instead, .live() binds a special handler to the root of the DOM tree.
现在,重新阅读后,我想知道您到底在问什么。您还必须确保每个 <div>
必须有一个唯一的 ID。可以考虑你.next('div')
而不是 .closest()
根据评论中的讨论,我会使用 .next('div') 查看昨天问题 http://jsfiddle.net/ycpgD/ 中修改后的 jsfiddle
另外,我强烈建议使用唯一 ID。如果它们不能是唯一的,就让它们上课。
关于php - 将 .slideToggle 与动态生成的 div 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6529596/