繁体   English   中英

jquery根据布尔值显示隐藏元素boolean

[英]jquery show hide element according to boolean value boolean

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

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>

注意:以上仅适用于两者,并且是非常硬编码的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM