1

必须根据一些逻辑检查来控制一些 dom 元素的可见性——我真的很想在 jquery 中这样的东西:

$('.FirstPanel').visible = (condition == 1 || othercondition == true);
$('.SecondPanel').visible = (condition > 3 || othercondition == false);
$('.ThirdPanel').visible = (condition < 3 || stillanothercondition = 'asdf');
etc

当然,我可以使用 if 或 switch 语句和调用来表达上面的代码$('.FirstPanel').hide()……但它需要很多倍的代码行数。

if(condition == 1 || othercondition == true) {
    $('.FirstPanel').show();
    $('.SecondPanel').hide();
    $('.ThirdPanel').hide();
} else if (condition > 3 || othercondition == false) {
    $('.FirstPanel').hide();
    $('.SecondPanel').show();
    $('.ThirdPanel').hide();
} etc

我觉得我错过了一些明显的东西。谢谢


2012.09.24 更新

感谢大家的回答 - 切换方法是票(见下面 Michaël Witrant 接受的答案)

4

2 回答 2

3
$('.FirstPanel').toggle(condition == 1 || othercondition == true);
$('.SecondPanel').toggle(condition > 3 || othercondition == false);
$('.ThirdPanel').toggle(condition < 3 || stillanothercondition = 'asdf');

http://api.jquery.com/toggle/

于 2012-09-13T17:58:04.247 回答
0

尝试类似:

$(".element").css("display", function() { value = (condition == 1 || othercondition == true); if (value) { return 'block'; /*or 'inline' or 'inline-block'*/ } 
return 'none'; });
于 2012-09-13T17:55:26.600 回答