mootools |切换事件

时间:2014-01-15 14:01:14

标签: javascript-events click toggle mootools

我有mootools代码:

document.getElements('.toggler').addEvent('click', function(e){

var target  = this.getChildren('i');
console.log(target);

if (target.hasClass('icon-minus')) {
   console.log('hasclass - minus'); 
   target.addClass('icon-plus').removeClass('icon-minus');
   this.getNext('div').hide();
} else {    
   console.log('hasclass - plus');
   target.addClass('icon-minus').removeClass('icon-plus');
   this.getNext('div').show();
}                           
});

我的HTML布局:

<div class="filter">
   <sup class="toggler">
      <i class="icon-minus"></i>
   </sup>
</div>

但如果我点击切换器,我会得到:

1: Object[i.icon-minus]
hasclass - minus
2: Object[i.icon-plus]
hasclass - minus
3: Object[i.icon-plus]
hasclass - minus

这是一个错误! 如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

使用.getChildren()时,除了Mootools集合外,您不会获得任何元素。一个数组。

看起来像这样:

[i.icon-minus, $family: function, $constructor: function,// etc

如果你这样做 你得到console.log(target.hasClass('icon-minus'))

[false, $family: function, $constructor: function, each: function, // etc

这意味着.hasClass可以工作,但它的布尔值在集合中。

所以,我的建议是:

如果,每个i内只有一个.toggler使用:

var target  = this.getFirst('i');
//or
var target  = this.getElement('i');

如果 i内有多个.toggler使用:

target.each(function(thisElement){

    if (thisElement.hasClass('icon-minus')) {
        thisElement.addClass('icon-plus').removeClass('icon-minus');
        this.getNext('div').hide();
    } else {
        thisElement.addClass('icon-minus').removeClass('icon-plus');
        this.getNext('div').show();
    }
}

Fiddle

答案 1 :(得分:2)

另一种写作方式是:

document.getElements('.toggler').addEvent('click', function(e){
    e && e.stop();
    // the i and the div won't change. only get them from DOM once.
    var i = this.retrieve('i', this.getElement('i')),
        next = this.retrieve('next', this.getNext('div')),
        // keep state in storage also, no need to query dom all the time.
        isCollapsed = this.retrieve('state', i.hasClass('icon-plus'));

    // based upon current state (which we don't need in DOM after the first time)
    // calls either hide or show dynamically.
    next[['hide', 'show'][+isCollapsed]]();
    // all we want is to swap the classes, use toggleClass. 
    i.toggleClass('icon-plus').toggleClass('icon-minus');
    // save new state
    this.store('state', !isCollapsed);
});

http://jsfiddle.net/dimitar/3ZY9Q/

这可以最大限度地减少你的dom查找并从内存中工作(元素存储) - 它还会删除if / then / else代码的复杂性。