[英]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.