1

我想在点击时切换添加/删除事件监听器。有人能指出我如何改进我的代码吗?

我在 Stackoverflow 上阅读了许多答案,但没有一个对我有帮助。

这是一个学习工具,将指针悬停在显示的数字上会使中心立方体旋转以显示相同的数字。

当页面加载时,一个事件监听器被添加到中心立方体,我编写了一个小 jQuery 来将监听器添加到任何单击的立方体,这样它们也会显示指针悬停的数字。

在 Chrome 中运行,在 Opera 中运行。FF 认为它的 Salvador Dali 和 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(){});
4

1 回答 1

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

这样你就不会与其他处理程序混淆..

希望能帮助到你...

于 2013-04-05T18:13:09.333 回答