1

I'm creating a confirm message box using this plugin.

<input type="button" id="deleteByID" value="Delete Item By ID" />
<div id="modal">
    <div id="heading">
        Are you sure you want to do that?
    </div>
    <div id="content">
        <a href="#" id='revealYes' class="button green close"><img src="images/tick.png">OK</a>
        <a href="#" id='revealNo' class="button red close"><img src="images/cross.png">Cancel</a>
    </div>
</div>
$('#deleteByID').click(function(e) {
   $('#modal').reveal({
      animation: 'fade',
      animationspeed: 320,
      closeonbackgroundclick: true,
      dismissmodalclass: 'close'
   });
   $('#revealYes,#revealNo').click(function(){
      var choice = $(this).text();
      if(choice == 'OK'){
         deleteItemInCart(item5);
         updateQtyLabel('qtyItem');
      }else{
         return false;
      }
   });  
});
  1. I want to change the blog #modal into dynamic div as this function, how can I call this function in my page to create a #modal div as html above.

     function messageBox(heading, confirmMsg, cancelMsg){
       var box = ' <div id="modal"><div id="heading">'+heading+'</div><div id="content"> <a href="#" id="revealYes" class="button green close"><img src="images/tick.png">'+confirmMsg+'</a> <a href="#" id="revealNo" class="button red close"><img src="images/cross.png">'+cancelMsg+'</a>';
       return box;
    }
    
  2. In my console,function deleteItemInCart() increase executing time + 1 every time I click on OK button. I meant, when I click on the OK button 1st time, the function called 1 time then the message box closed. Then click on OK button 2nd time, the function is call 2 times in my console. Any idea what could be causing this

Any help would be much appreciated, thank you.

4

1 回答 1

3

每次单击时,$('#deleteByID')您都会为此创建一个新的单击处理程序,$('#revealYes,#revealNo')这意味着执行的代码

var choice = $(this).text();
if (choice == 'OK') {
    deleteItemInCart(item5);
    updateQtyLabel('qtyItem');
} else {
    return false;
}

每点击一次就会多执行一次$('#deleteByID')

更改您的代码,以便单击处理程序$('#revealYes,#revealNo')位于其他单击处理程序之外

$('#deleteByID').click(function (e) {
    if($('#modal').length == 0)
        $('body').append(messageBox('heading','confirm','cancel'))
    $('#modal').reveal({
        animation: 'fade',
        animationspeed: 320,
        closeonbackgroundclick: true,
        dismissmodalclass: 'close'
    });

});

$(document).on('click','#revealYes,#revealNo',function (e) {
    var choice = $(e.target).text();
    if (choice == 'OK') {
        deleteItemInCart(item5);
        updateQtyLabel('qtyItem');
    } else {
        return false;
    }
});

使用委托处理程序而不是绑定处理程序将处理程序添加到动态元素

于 2013-09-06T01:40:07.540 回答