[英]Javascript firing event more than once
我有一个模态,可以通过另一个php脚本获取其内容。 然后,将使用用户选择的ID加载内容,并使他们能够编辑内容。
模态本身被加载在单独的动态容器中的上方。
问题是这样的:
首次点击模式广告:已触发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>
您可以仅使用一次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();
但是最好的选择是不要将此事件嵌套在点击处理程序中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.