2013-06-03 87 views
0

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

回答

2

需要使用事件代表团使用事件冒泡的概念,重视事件的元素...

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

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

element - 动态创建的实体要

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

入住这看看它提醒标识。

0

在元素

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

请试试这每一个环。

+0

'on'是优选的方法。 –

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

一种解决方案是使用事件委托事件与.on()方法附加其中:

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

另一种解决方案是克隆与事件的元素,只是通过true.clone()方法:

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

参考文献:

相关问题