我正在使用 Ajax 请求创建元素。我想将一个函数绑定(bind)到每个元素以在其单击事件中运行。我怎样才能做到这一点?这是我生成元素的代码。
ajaxCall("/getItems","POST",data,function(result){
var element = $('.item').first();
$('#item-list-section').empty();
for(var i = 0; i < result.items.length; i++){
var clone = element.clone();
clone.attr("id", result.items[i].itemId);
clone.find('.item-price').html("<h4>25</h4>");
if(result.items[i].itemName.length > 20){
clone.find('.item-name').css('overflow','hidden');
clone.attr('title', result.items[i].itemName )
}
clone.find('.item-name').html("<h4>"+ result.items[i].itemName + "</h4>");
//clone.mousedown(onItemClick(clone));
clone.draggable({
revert : false,
zIndex: 1,
containment: "window",
opacity: 0.5,
cursor: "move",
helper: function() { return $(this).clone().appendTo('body').show(); }
});
$('#item-list-section').append(clone);
}
});
最佳答案
需要使用事件委托(delegate),它使用事件冒泡的概念将事件附加到元素...
$(staticContainer).on("click", element , function(event){
// Code here
});
staticContainer
-- 始终存在于 DOM 中的元素。越接近动态创建的元素越好。
element
- 动态创建的要附加事件的实体
关于javascript - 将点击事件函数绑定(bind)到动态创建的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16891125/