2013-04-05 171 views
1

我想點擊添加/刪除事件監聽器。有人能指出我可以如何改進我的代碼嗎?如何從DOM元素中刪除事件偵聽器?

我讀過Stackoverflow上的一些答案,但沒有人幫助過我。

這是一個學習工具,將指針懸停在顯示的數字上可使中心立方體旋轉以顯示相同的數字。

當頁面加載一個事件監聽器被添加到中心多維數據集,我寫了一個小jQuery來添加監聽器到任何點擊的多維數據集,所以他們也將顯示指針懸停的數量。

適用於Chrome,適用於Opera。 FF認爲它的薩爾瓦多達利和IE ...呃!

How it works at the moment

事件監聽器添加在頁面加載

var thisCube = '.two'; 
var init = function() { 
    var box = document.querySelector(thisCube).children[0], 
     showPanelButtons = document.querySelectorAll('#hover-change li'), 
     panelClassName = 'show-front', 

     hover = function(event){ 
     box.removeClassName(panelClassName); 
     panelClassName = event.target.className; 
     box.addClassName(panelClassName); 
     }; 

    for (var i=0, len = showPanelButtons.length; i < len; i++) { 
    showPanelButtons[i].addEventListener('mouseover', hover, false); 
    } 

}; 

window.addEventListener('DOMContentLoaded', init, false); 

jQuery來添加新的監聽

$('.one, .three, .four, .five, .six, .seven, .eight, .nine').click(function() { 
    thisCube = $(this).data('id'); 
    init(); 
}); 

我敢肯定,我不正確,因此,添加事件偵聽器當我閱讀其他解決方案時,正在引起我的麻煩。

我沒有爲這篇文章構建一個jsfiddle,因爲發佈所有相關代碼的新規則會使這篇文章太大。如果有人想在jsfiddle上看到它,請詢問。

Built on this demo

- 編輯 -

我試圖將此代碼添加到添加一個類rotate如果一個元素具有類已經我刪除rotate和刪除事件偵聽器。它不會刪除事件監聽器。

$('.one, .two, .three, .four, .five, .six, .seven, .eight, .nine').on('click', function() { 

    if($(this).hasClass('rotate')) 
    { 
     $(this).removeClass('rotate'); 
     alert('remove ' + $(this).attr("class")); 
     $(this).off('click'); 
    } else { 
     $(this).addClass('rotate'); 
     alert('add ' + $(this).attr("class")); 
     thisCube = $(this).data('id'); 
     init(); 
    } 
}); 

- 我的解決方案 -

$('.container').click(function(){ 
    $(this).toggleClass('rotate'); 
}); 

$('#hover-change').children().hover(function(){ 
    $('.rotate > #cube').removeClass(); 
    $('.rotate > #cube').addClass($(this).attr('class')); 
}, 
function(){}); 

回答

3

您可以使用jQuery.on添加事件偵聽器和jQuery.off將其刪除。

//Add 
$('.one, .three, .four, .five, .six, .seven, .eight, .nine').on('click', function() { 
    thisCube = $(this).data('id'); 
    init(); 
}); 

// Remove 
$('.one, .three, .four, .five, .six, .seven, .eight, .nine').off('click'); 

可以使用事件命名空間以及:

//Add 
    $('.one, .three, .four, .five, .six, .seven, .eight, .nine').on('click.MyNamespace', function() { 
     thisCube = $(this).data('id'); 
     init(); 
    }); 

// Remove 
    $('.one, .three, .four, .five, .six, .seven, .eight, .nine').off('click.MyNamespace'); 

這樣,你不惹其他處理..

希望它可以幫助...

+0

感謝您帖子。我使用jQuery'.on'來添加監聽器,它的工作可愛,然後改變了代碼,所以第二次點擊會刪除監聽器,但是這對我不起作用。如果你有時間可以看看我的問題的結尾,我添加了我嘗試使用的代碼。 – 2013-04-06 18:19:18

+0

我添加了我的解決方案。它避免了事件監聽器:) – 2013-04-07 00:27:24