2012-10-29 169 views
0
$(document).on('click', '#slider_icons_wrapper.play', function(event) { 
     var slider_icons_wrapper = $('#slider_icons_wrapper'); 

     slider_icons_wrapper.attr('class', 'pause'); 
     autoSlider(cur_img_div_pos); 
     showButton('play_icon'); 
     console.log('play'); 
    }); 

    $(document).on('click', '#slider_icons_wrapper.pause', function(event) { 
     var slider_icons_wrapper = $('#slider_icons_wrapper'); 

     slider_icons_wrapper.attr('class', 'play'); 
     clearInterval(inter); 
     showButton('pause_icon'); 
     console.log('pause'); 
    }); 

這段代碼第一次加載文檔時工作正常。 當用戶通過ajax調用(文檔不刷新)導航到另一個頁面並返回包含#slider_icons_wrapper div的頁面時,該函數在用戶單擊該div時執行兩次。如果用戶再次導航並返回,則該功能執行3次,等等!jQuery點擊事件在ajax調用後再次執行函數

我在做什麼錯?

編輯#1

當用戶導航到另一頁,元素#slider_icons_wrapper從DOM移除。當它通過ajax調用返回時,點擊事件每次都會在更多時間觸發。我試圖在用戶離開這個頁面時解除這個點擊事件,但是同樣的事情發生了

+0

看起來好像存在選擇器衝突。我會將HTML中的ID更改爲'#slider_icons_wrapper_play'和'#slider_icons_wrapper_pause'。 – Chris

+0

我想選擇id =「slider_icons_wrapper」和class =「play」或「pause」的div, – kapantzak

回答

0

似乎將事件偵聽器添加到每個頁面返回的文檔中。嘗試將他們的document.ready -

function init(e){ 

    $(document).on('click', '#slider_icons_wrapper.play', function(event) { 
     var slider_icons_wrapper = $('#slider_icons_wrapper'); 

     slider_icons_wrapper.attr('class', 'pause'); 
     autoSlider(cur_img_div_pos); 
     showButton('play_icon'); 
     console.log('play'); 
    }); 

    $(document).on('click', '#slider_icons_wrapper.pause', function(event) { 
     var slider_icons_wrapper = $('#slider_icons_wrapper'); 

     slider_icons_wrapper.attr('class', 'play'); 
     clearInterval(inter); 
     showButton('pause_icon'); 
     console.log('pause'); 
    }); 

} 

$(document).ready(init); 

user1026361也使得一個好點再次加入他們之前刪除你的聽衆。然而,我相信沒有選擇器的情況下使用.off()將通過.on()刪除添加到該元素的所有偵聽器。如果採用.off().on()方法,我會建議使用命名空間:

$(document).off('click.clickPlay').on('click.clickPlay', '#slider_icons_wrapper.play', function(event) { 
    ... 
}); 

$(document).off('click.clickPause').on('click.clickPause', '#slider_icons_wrapper.pause', function(event) { 
    ... 
}); 
+0

謝謝你的幫助!我也嘗試了你的想法和user1026361,但它不起作用。 – kapantzak

+0

解決!謝謝! – kapantzak

+0

沒問題,很高興我能幫上忙。 – logic8

0

如果你正在執行你的事件處理程序在「導航和返回」時被設置的代碼,你可能會分配多個處理程序事件。

使用try這些語句:

$(document).off().on('click', '#slider_icons_wrapper.play', function(event) { 

$(document).off().on('click', '#slider_icons_wrapper.pause', function(event) { 

來重新分配他們

你應該總是很清楚你的處理程序之前清除處理程序和小心,在那裏你指定他們的地方只有每個頁面瀏覽見過一次。

+0

.off()將刪除所有事件處理程序,最好是使用.off('click') –

+0

烘焙是正確的。因爲你知道元素上的事件,所以你可以明確地清除它。我通常刪除所有之前添加所有,所以上述工作對我更好 – user1026361

相關問題