在JQuery中显示和隐藏对象

我想根据某些条件显示和隐藏对象(div,文本或btns)。

在C#中,我们可以编写如下内容来减少编码量:

txtA.visible = (type == "A"); txtB.visible = (type == "B"); txtC.visible = (type == "C"); 

在JQuery中,为了显示和隐藏,我使用.show()和.hide()方法。 但是,我必须为这个简单的function编写许多行。 例如:

 if (type == "A") $("#txtA").show(); else $("#txtA").hide(); if (type == "B") $("#txtB").show(); else $("#txtB").hide(); if (type == "C") $("#txtC").show(); else $("#txtC").hide(); 

无论如何用更少的线来实现相同的function? 谢谢。

.toggle(showOrHide)允许使用布尔值来显示或隐藏元素。

您可以将示例重写为如下所示:

 $("#txtA").toggle(type === "A"); $("#txtB").toggle(type === "B"); $("#txtC").toggle(type === "C"); 

关于jsfiddle的例子

使用三元运算符:

 (type == "A") ? $("#txtA").show() : $("#txtA").hide(); 

看看JQuery切换 !

这将显示当前类型并隐藏所有兄弟元素(我假设它们被放置在容器内)

 // Remember ids are case sensitive var type = 'A'; $('#txt' + type).show() // Show the current type .siblings().hide(); // Hide all other elements 

小提琴: http //jsfiddle.net/garreh/4JkGm/

如果您的兄弟元素并不总是您要隐藏的类型,只需在其上标记filter:

 $('#txt' + type) .show() // Show the current type .siblings() .filter(function() { return (this.id.match(/^txt[AC]$/)) }).hide(); // Hide all other elements 

小提琴: http //jsfiddle.net/garreh/4JkGm/1/