我在编写委托(delegate)函数以使其适用于每个动态插入的 div 时遇到语法问题。
容器是“column”,在“column”中我插入了许多“dragbox”:
<div class="dragbox">
<h2>Actions
<button type="button">
<i class="fa fa-sort-desc"></i>
</button>
</h2>
<div class="dragbox-content">
content of the dragbox
</div>
</div>
因此,在每个“dragbox”中,我都有一个“h2”和一个“dragbox-content”。我的目标是当我单击“h2”时切换“dragbox-content”。因为“dragbox”是动态插入的,所以我发现我需要使用“delegate”函数才能使其工作:
jQuery click not working for dynamically created items
jquery .delegate and dynamic content
但是,我的问题是我不知道如何编写它以使每个“dragbox”具有相同的行为。
这是我迄今为止尝试过的:
$('.column').children('.dragbox').each(function(){
$(this).delegate("h2", "click", function(){
$(this).siblings('.dragbox-content').toggle();
}).end();
});
这在静态“dragbox”上工作得很好,但在动态插入的“dragbox”上却不起作用。我确实需要使用“each”函数,因为切换事件对于每个“dragbox”都是独立的。我不希望当我单击其中一个拖动框的标题时切换所有拖动框。
我使用的库是 jQuery 和 jQuery-ui。
最佳答案
从列中进行委托(delegate):
$(".column").delegate(".dragbox h2", "click", function() {
$(this).siblings('.dragbox-content').toggle();
}).end();
对于现代版本的 jQuery(从 1.7 开始,于 2011 年 11 月发布),您可以使用 .on
,它与 .delegate
类似,但参数已切换:
$(".column").on("click", ".dragbox h2", function() {
$(this).siblings('.dragbox-content').toggle();
}).end();
我个人尝试从文档中进行所有委托(delegate):
$(document).on("click", ".column .dragbox h2", function() {
$(this).siblings('.dragbox-content').toggle();
}).end();
这样我就可以随时进行事件处理初始化,而不必担心内容是否准备好。
关于JavaScript : how to use delegate on each dynamically added div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32229811/