简体   繁体   English

动态产生div的多次点击操作被调用

[英]Click action getting called multiple times for dynamically generated div

On a ajax call I am generating a div and also creating a click action associated with this div. 在ajax调用中,我正在生成一个div,并且还创建了与此div相关联的click动作。 I assign the div a unique Id based on key value coming from data. 我根据来自数据的键值为div分配一个唯一的ID。 Problem doing this 这样做有问题

var $orderData = $('<div><table width="100%"><tr><td nowrap width="15%">'+valX1
                + '</td><td width="10%" class="imgClass" ><img src=' 
                + imgPath + ' id="img_'+serId+'" /></td> 
                + <td nowrap width="25%">' + customerName 
                + '</td><td nowrap width="25%">' + orderPendingCount 
                + '</td><td nowrap width="25%">' 
                + plant+'</td></tr>' + '<tr><td nowrap width="15%">' + modelName 
                + '</td><td></td><td nowrap width="25%">' 
                + totalNo + '</td><td nowrap width="25%">' 
                + deliveredTotal+'</td><td nowrap width="25%">'
                + salesPersonName + '</td></tr></table></div>'  );


$('body').on('click', '#img_'+serId, function(){
    $('body').css('cursor', 'default');
    alert(serId);
    return false;
});

Click action gets called correctly. 单击操作会正确调用。

Issue occurs when same serId comes with the ajax call. 当ajax调用附带相同的serId时,就会发生问题。 I am assuming the click action gets created again for the div. 我假设再次为div创建了点击操作。 This causes repeated click action call. 这会导致重复的点击动作调用。

Is there a way I can clear the div action script and div before I create it again 有没有办法可以在再次创建之前清除div操作脚本和div

you should just use a class what ever has that class will automatically get that event after: 您应该只使用一个类,该类拥有的类将在以下情况后自动获取该事件:

$('body').on('click', '.divImgClass', function(){
    $('body').css('cursor', 'default');
    alert(serId);
    return false;
});

Then you won't have to reset the event in the first place it will just be there on that class 然后,您不必一开始就重置事件,它只会在该课程上显示

insert the script before your regenerate the div and try 在重新生成div之前插入脚本并尝试

if($('#divid').length != 0) {
  $('#divid').remove();
}

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

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