Showing and Hiding of Objects in JQuery

不羁岁月 提交于 2019-12-10 21:46:39

问题


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? Thanks.


回答1:


.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




回答2:


Use the ternary operator:

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



回答3:


have a look at JQuery toggle!




回答4:


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/



来源:https://stackoverflow.com/questions/6280499/showing-and-hiding-of-objects-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!