[英]Hide / show div using one button in jQuery
I am trying to hide one element and show the other when when button is clicked and switch around when it is clicked again. 我试图隐藏一个元素,当单击按钮时显示另一个元素,并在再次单击时切换。
I came up with something like this but this isn't going to work... 我想出了类似的东西,但是这行不通...
jQuery("#wcvat-toggle").click(function() { jQuery("#excltaxout").show(); jQuery("#incltaxout").hide(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a id="wcvat-toggle"> <span id="incltaxout">Including Tax</span> <span id="excltaxout">Excluding Tax</span> </a>
However this will always show the #excltaxout
. 但是,这将始终显示#excltaxout
。 Any suggestions? 有什么建议么?
To make this work - and assuming that one of those elements starts hidden - you can simply call toggle()
on them both at the same time. 为了使这项工作有效-并假设其中一个元素开始隐藏-您可以简单地同时在两个元素上调用toggle()
。 This will invert their display
states. 这将反转其display
状态。
jQuery(function($) { $("#wcvat-toggle").click(function() { $("#excltaxout, #incltaxout").toggle(); }); });
#excltaxout { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a id="wcvat-toggle"> <span id="incltaxout">Including Tax</span> <span id="excltaxout">Excluding Tax</span> </a>
You can use jQuery's .toggle()
: 您可以使用jQuery的.toggle()
:
Display or hide the matched elements. 显示或隐藏匹配的元素。
$("#wcvat-toggle").click(() => { $("#incltaxout").toggle(); $("#excltaxout").toggle(); });
#incltaxout {display:none}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a id="wcvat-toggle"> <span id="incltaxout">Including Tax</span> <span id="excltaxout">Excluding Tax</span> </a>
Note however that this only works if one element is hidden by default, if not you will hide/show both at once. 但是请注意,这仅在默认情况下隐藏一个元素时才有效,否则,您将一次隐藏/显示两个元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.