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

时间:2013-06-03 06:32:22

标签: javascript jquery

我正在使用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);
  }
});

6 个答案:

答案 0 :(得分:2)

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

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

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

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

答案 1 :(得分:0)

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

选中此项以查明是否提醒该ID。

答案 2 :(得分:0)

在每个元素循环中

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

答案 3 :(得分:0)

$(clone).bind("click",function(event){
// your code
});

请试一试。

答案 4 :(得分:0)

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

答案 5 :(得分:0)

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

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

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

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

参考文献:

相关问题