Showing and Hiding of Objects in JQuery
I would like to show and hide the objects (divs, texts or btns) according to some conditions.
In C#, we can write like the following to reduce amount of codings:
txtA.visible = (type == "A");
txtB.visible = (type == "B");
txtC.visible = (type == "C");
In JQuery, to show and hide, I use .show() and .hide() methods. But, I have to write many lines for that simple feature. For eg:
if (type == "A")
$("#txtA").show();
else
$("#txtA").hide();
if (type == "B")
$("#txtB").show();
else
$("#txtB").hide();
if (type == "C")
$("#txtC").show();
else
$("#txtC").hide();
Is there anyway to achieve the same functionality with fewer lines? Thank开发者_运维问答s.
.toggle(showOrHide)
allows for a boolean to show or hide the element.
You could rewrite your example to look like this:
$("#txtA").toggle(type === "A");
$("#txtB").toggle(type === "B");
$("#txtC").toggle(type === "C");
Example on jsfiddle
Use the ternary operator:
(type == "A") ? $("#txtA").show() : $("#txtA").hide();
have a look at JQuery toggle!
This will show the current type and hide all siblings elements (I assume they are placed inside a container)
// Remember ids are case sensitive
var type = 'A';
$('#txt' + type).show() // Show the current type
.siblings().hide(); // Hide all other elements
Fiddle: http://jsfiddle.net/garreh/4JkGm/
If your sibling elements aren't always the type you want to hide just tag a filter onto it:
$('#txt' + type)
.show() // Show the current type
.siblings()
.filter(function() {
return (this.id.match(/^txt[A-C]$/))
}).hide(); // Hide all other elements
Fiddle: http://jsfiddle.net/garreh/4JkGm/1/
精彩评论