2013-06-03 193 views
0

我将绑定点击事件绑定到动态创建的元素。这是我的动态元素创建方法。onclick方法不起作用

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.on('click',function(){ 
      showToolTip(); 
     }); 

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

这是点击事件功能!

function showToolTip(){ 
    $newDiv = $('<div></div>'); 
    $newDiv.css("display", "none"); 
    $newDiv.addClass('tooltip'); 
    $newDiv.append('adfhadfhadfhadfh') 
    $newDiv.appendTo("body"); 
    $newDiv.fadeIn().css(({ left: e.pageX, top: e.pageY })); 
} 

我用萤火虫调试点,但它不会从点击功能中断!我绑定点击事件的方式是错误的!与此

clone.on('click',function(){ 

+0

凡'$ newDiv'分配? – andyb

回答

1

如果您单击事件处理程序添加到'#item-list-section'元素的for循环之外,它将在以下内容中动态创建元素:

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

在这里,您可以用克隆的元素类型或任何标识类来代替element,正如您通常那样。如果克隆的因素是<div class="myDiv">,例如,你可以使用'div''.myDiv'

例如,如果你的标记结束了是这样的:

<div id="item-list-section"> 
    <div class="myClonedElement"></div> 
    <div class="myClonedElement"></div> 
    <div class="myClonedElement"></div> 
</div> 

你可以单击事件绑定到使用克隆的元素容器:

$('#item-list-section').on('click', '.myClonedElement', function() { 
    showTooltip(); 
}); 

这样,您就无需再创建一个新的单击事件处理程序对每个克隆元素。你有一个迎合所有人。

JSFiddle example

1

替换代码

$(document).on('click', '#' + result.items[i].itemId, function(){ 

参考:Understanding Event Delegation

+2

您可能需要''#'+ result.items [i] .itemId'。 –

0

是否确定原始对象没有已经定义的点击回调?

尝试:

clone.unbind("click"); 

之前设置你的回调