Jquery显示隐藏元素根据布尔值布尔



我使用这些行来显示隐藏一些元素:

function isActive()
{
     $("#id1").hide();
     $("#id2").show();
}

但是我需要改变上面的行,使元素显示或隐藏根据bool值:

function isActive(toShow)
{
     $("#id1").hide();
     $("#id2").show();
}

实现它的最佳方式是什么?

使用$.fn.toggle(Boolean: display):

function isActive(toShow)
{
     $("#id1").toggle(!toShow);  // Hide when toShow = true, show when toShow = false
     $("#id2").toggle(!!toShow); // Hide when toShow = false, show when toShow = true
}

确保toShow是布尔值是很重要的。

这完全是更好的方法,但最好的方法是设置事件处理程序并使用类:

$(function () {
  $(".cont").hide();
  $(".trig").click(function () {
    $(".cont").hide();
    $($(this).attr("href")).show();
  });
});
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<a class="trig" href="#id-1">Display 1</a>
<a class="trig" href="#id-2">Display 2</a>
<a class="trig" href="#id-3">Display 3</a>
<div id="id-1" class="cont">Contents of Item 1</div>
<div id="id-2" class="cont">Contents of Item 2</div>
<div id="id-3" class="cont">Contents of Item 3</div>

如果您已经正确设置了两个元素(一个隐藏,一个可见),您可以使用以下代码来切换它们的可见性:

$("#id1, #id2").toggle();

示例如下:

<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<a href="#" onclick='$("#id1, #id2").toggle(); return false;'>Toggle Display</a>
<div id="id1" style="display: none;">Contents of Item 1</div>
<div id="id2">Contents of Item 2</div>

注意:上面的操作只适用于两个,并且它是硬编码的。

最新更新