繁体   English   中英

将单击事件函数绑定到动态创建的元素

[英]Bind click event function to a dynamically-created element

我正在使用Ajax请求创建元素。 我想将一个函数绑定到每个元素以在其click事件中运行。 我怎样才能做到这一点? 这是我生成元素的代码。

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);
  }
});

需要使用事件委托使用事件冒泡的概念将事件附加到元素...

$(staticContainer).on("click", element , function(event){
  // Code here
});

staticContainer - 始终存在于DOM中的元素。 它越接近动态创建的元素越好。

element - 要将事件附加到的动态创建的实体

$(clone).on("click", function(event){
  alert($(this).attr('id'));
});

检查这一点,看看它是否提醒id。

在每个元素循环中

$(clone).each(function(index, value) { 
$(value).on("click", function(event){
  alert($(this).text());
});
}
$(clone).bind("click",function(event){
// your code
});

请试试这个。

$(document).on("click",value, function(event){
  alert($(this).text());
});

一种解决方案是使用.on()方法使用事件委派:

$('#item-list-section').on('click', '.item', function () {
    // do something
});

另一个解决方案是使用事件克隆你的元素,只需将true传递给你的.clone()方法:

var clone = element.clone(true);
  • 请注意,如果var element = $('.item').first(); ,这将起作用var element = $('.item').first(); 在页面上是静态的。

参考文献:

暂无
暂无

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

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