嗯..不清楚你真正想要做什么。制作一个实用功能(插件?)来处理各种隐藏/显示方法?试试这个(http://jsfiddle.net/duBbE/9/):
function toggleMe(options) {
var _selector = !!options.sSelector ? options.sSelector : '.toggle'; // Pass any selector (can be #idSomething or .classSomething)
var _method = !!options.sMethod ? options.sMethod : 'toggle'; // Pass in method let default be used ('toggle' will set it to other value of current state(show/hide))
var _time = !!options.nTime ? options.nTime: 800; // Pass class in time to be used with certain methods
//console.log(options);
$(_selector).each(function(event){
//console.log(this);
try {
if(_method == 'slideUp') {
$(this).slideUp(_time);
} else if(_method == 'slideToggle') {
$(this).slideToggle(_time);
} else if(_method == 'toggle') {
this.style.display = this.style.display == 'none' ? 'block': 'none';
} else if(_method == 'hide') {
$(this).hide();
} else if(_method == 'show') {
$(this).show();
} else {
console.log('here in NADA Land');
}
} catch(err) {
console.log(err);
}
});
}; // End Function
然后初始化、绑定或更通用地调用它。我认为这应该让你开始。
$(function() {
toggleMe({sSelector: '.toggle3', sMethod: 'toggle'});
toggleMe({sSelector: '.toggle-box3', sMethod: 'slideToggle'});
toggleMe({sSelector: '.toggle-box2', sMethod: 'slideUp'});
toggleMe({sSelector: '.toggle1', sMethod: 'hide'});
$('.toggle-close1').on('click', function(event) {
toggleMe({sSelector: '.toggle1', sMethod: 'toggle'});
console.log(event.target.innerHTML.indexOf('Close'))
event.target.innerHTML = $('.toggle1')[0].style.display == 'block' ? 'Close Toggle 1': 'Open Toggle 1';
});
});
您可以将方法 if/else 换成 case-switch、expand、add default case 等。