TTC*_*TCG 3 javascript jquery coding-style
我想根据某些条件显示和隐藏对象(div,文本或btns).
在C#中,我们可以编写如下内容来减少编码量:
txtA.visible = (type == "A");
txtB.visible = (type == "B");
txtC.visible = (type == "C");
Run Code Online (Sandbox Code Playgroud)
在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();
Run Code Online (Sandbox Code Playgroud)
无论如何,用更少的线来实现相同的功能?谢谢.
Mar*_*man 10
.toggle(showOrHide) 允许布尔值显示或隐藏元素.
你可以重写你的例子看起来像这样:
$("#txtA").toggle(type === "A");
$("#txtB").toggle(type === "B");
$("#txtC").toggle(type === "C");
Run Code Online (Sandbox Code Playgroud)
使用三元运算符:
(type == "A") ? $("#txtA").show() : $("#txtA").hide();
Run Code Online (Sandbox Code Playgroud)