gpt4 book ai didi

javascript - mootools |切换器事件

转载 作者:行者123 更新时间:2023-11-30 10:22:02 25 4
gpt4 key购买 nike

我有 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

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

最佳答案

另一种写法是:

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 代码的复杂性。

关于javascript - mootools |切换器事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21139460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com