动态创建的元素上的EACH事件绑定



我有这个函数:

$(".card").each(function() {
$(this)
.closest('.collapse-group')
.find('.btn')
.toggle($(this).text().length > 16);
});

但当元素被动态附加时,我需要对其进行转换,例如,我知道如何对click函数进行转换,但在EACH-no:上

$(document).on('click', '.btn', function(e) {
e.preventDefault();
var $this = $(this);
var $collapse = $this.closest('.collapse-group').find('.collapse');
$collapse.collapse('toggle');
}); //- this func works
$(document).on('each', ".card", function() {
$(this)
.closest('.collapse-group')
.find('.btn')
.toggle($(this).text().length > 16);
});//??? - this func does not work

把它直接插入我附加卡片的块下面不起作用:

var card =
`<hr>
<h3>
<p class="text-center " >${title}</p>
</h3>
<img class="col-12 ml-auto col-12 mr-auto" src=${images}>
<div class="span4 collapse-group">
<div class="text-center">
<p><a class="btn btn-md btn-outline-dark btn-square" href="#">Check &raquo;</a></p>
</div>
<div class="collapse">
<div class="card card-body">
${text}
</div>
</div>
</div>`
$('.container').append(card)
$(document).find(".card").each(function() {
$(this)
.closest('.collapse-group')
.find('.btn')
.toggle($(this).text().length > 16);
});

each不是事件,因此不能与.on一起使用。尝试以下函数迭代卡片

$('.container').find(".card").each(function() {
var toggle = $(this).text().length > 16;
var collapseGroup = $(this).closest('.collapse-group');
collapseGroup.find('.btn').toggle(toggle);
});

最新更新