2015-07-21 81 views
0

我有一个通过另一个php脚本获取其内容的模式。内容随后加载用户选择的ID并使其能够编辑内容。不止一次Javascript触发事件

模态本身在一个单独的动态容器中加载到此之上。

的问题是这样的:

首次点击模式:1点触发的事件。

第二次:模态事件触发2次。

第三次:事件触发3次

等等...

我试过唯一ID和事件解除绑定,没有运气 - 任何想法? 我已经阅读了一些问题,但还没有遇到适合我的解决方案。

我的代码:

<script type="text/javascript"> 
$('.modal-launcher'+rates_randid+'').unbind('click').click(function(e){ 
    //modal and modal body selection 
    var modal = $('#modal_launcher'+modalid+''), modalBody = $('.modal-loader-content'+modalid+''); 
    //Gets ID for the rate that needs editing. 
    rateid = $(this).data('rateid'); 
    //on show of modal send ID and grab page/contents 
    modal.on('show.bs.modal', function() { 
      $.post('pages/edit_rate_modal.php?rateid='+rateid+'',{func:'edit'}) 
     .done(function(data){ 
      $('.modal-loader-content'+modalid+'').html(data); 
     }) 
     }) 
    //show modal 
     .modal(); 
    e.preventDefault(); 
}); 

$('#modal_launcher').on('hidden.bs.modal', function (e) { 
    $('.modal-loader-content').empty(); 
}) 
</script> 
+2

每次点击时,您都会绑定一个新的“show.bs.modal”事件。所以不要嵌套事件或至少尝试:'modal.one('show.bs.modal',function(){...});' –

+0

啊!谢谢!!太精彩了! 是的,当我添加下一页的模态窗口时,我将重写这部分内容。刚刚没有决定我想如何分享它。 虽然非常感谢! –

+0

你可以把它弹出来答案,所以我可以接受,作为解决方案 –

回答

1

您可以使用jQuery one()到模式显示事件只有一次绑定:

modal.one('show.bs.modal', function() { 
    $.post('pages/edit_rate_modal.php?rateid=' + rateid, { 
     func: 'edit' 
    }) 
     .done(function (data) { 
     $('.modal-loader-content' + modalid).html(data); 
    }) 
}) 
//show modal 
.modal(); 

但是你最好的选择将是不能嵌套单击处理程序内此事件。