Javascript JQuery中对象的显示和隐藏

Javascript JQuery中对象的显示和隐藏,javascript,jquery,coding-style,Javascript,Jquery,Coding Style,我想根据一些条件显示和隐藏对象(div、文本或btn) 在C#中,我们可以这样写以减少编码量: txtA.visible = (type == "A"); txtB.visible = (type == "B"); txtC.visible = (type == "C"); 在JQuery中,要显示和隐藏,我使用.show()和.hide()方法。 但是,我必须为这个简单的特性写很多行。例如: if (type == "A") $("#txtA").show(); else $("

我想根据一些条件显示和隐藏对象(div、文本或btn)

在C#中,我们可以这样写以减少编码量:

txtA.visible = (type == "A");
txtB.visible = (type == "B");
txtC.visible = (type == "C");
在JQuery中,要显示和隐藏,我使用.show()和.hide()方法。 但是,我必须为这个简单的特性写很多行。例如:

if (type == "A")
   $("#txtA").show();
else
   $("#txtA").hide();

if (type == "B")
   $("#txtB").show();
else
   $("#txtB").hide();

if (type == "C")
   $("#txtC").show();
else
   $("#txtC").hide();

有没有办法用更少的线来实现相同的功能?谢谢。

看一看

使用三元运算符:

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

这将显示当前类型并隐藏所有同级元素(我假设它们放置在容器中)

小提琴:

如果您的同级元素并不总是要隐藏的类型,只需在其上标记一个过滤器:

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

允许布尔值显示或隐藏元素

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

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

我认为在这种情况下,这不会减少代码大小,因为切换是有条件发生的。我不知道当您有很多元素时,这会减少多少代码,它只是在一行上添加条件<代码>if(type==“A”)$(“#txtA”).show();else$(“#txtA”).hide()几乎一样短。@Gary Green-我更喜欢你的解决方案
$("#txtA").toggle(type === "A");
$("#txtB").toggle(type === "B");
$("#txtC").toggle(type === "C");