簡體   English   中英

如何從DOM元素中刪除事件偵聽器?

[英]How to remove event listener from DOM element?

我想在點擊時切換添加/刪除事件監聽器。 有人可以指出我如何改進我的代碼?

我在Stackoverflow上閱讀了很多答案,但沒有人幫助過我。

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

當頁面加載時,事件監聽器被添加到中心多維數據集中,我寫了一個小jQuery來向任何單擊的多維數據集添加監聽器,這樣它們也將顯示指針懸停的數字。

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

它目前是如何運作的

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

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上看到它請問。

以此演示為基礎

- 編輯 -

我嘗試添加此代碼以添加類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(){});

您可以使用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');

您也可以使用Event Namespace:

//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');

這樣你就不會亂搞其他處理程序..

希望能幫助到你...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM