猿问

单击任一按钮时如何防止两个div同时切换内容

我有一个工作代码,但我面临的问题是,当您单击第一个按钮和第二个按钮时,两者都会显示内容。我不希望按钮同时处于活动状态。当一个按钮显示另一个按钮应该自动隐藏它的内容时,我希望它们独立于其他含义。后一个单击的按钮应优先切换前一个按钮以隐藏。


$("button").click(function() {

  $("p." + this.className).toggle("slow");

});

p {

  background: #dad;

  font-weight: bold;

  font-size: 16px;

}

<script src="https://code.jquery.com/jquery-3.4.1.js">

</script>

<button class="toggle1">Toggle 1</button>

<button class="toggle2">Toggle 2</button>

<p class="toggle1">Hiya</p>

<p class="toggle2">Such interesting text, eh?</p>


凤凰求蛊
浏览 80回答 3
3回答

慕少森

$("p[class*=toggle]:not(p." + this.className + ")").hide();$("button").click(function() {&nbsp; $("p[class*=toggle]:not(p." + this.className + ")").hide();&nbsp; $("p." + this.className).toggle("slow");});p {&nbsp; background: #dad;&nbsp; font-weight: bold;&nbsp; font-size: 16px;}<script src="https://code.jquery.com/jquery-3.4.1.js"></script><button class="toggle1">Toggle 1</button><button class="toggle2">Toggle 2</button><p class="toggle1">Hiya</p><p class="toggle2">Such interesting text, eh?</p>注意:- 首先您需要隐藏所有divs& 然后通过单击按钮,您需要使用this函数显示特定的 div。

陪伴而非守候

试试这个:-$("button").click(function() {&nbsp; $("p[class*=toggle]:not(p."+this.className+")").hide();&nbsp; $("p."+this.className).toggle("slow");});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><style type="text/css">p[class*=toggle] {display:none}p {&nbsp; background: #dad;&nbsp; font-weight: bold;&nbsp; font-size: 16px;}</style><button class="toggle1">Toggle 1</button><button class="toggle2">Toggle 2</button><button class="toggle3">Toggle 3</button><p class="toggle1">Hiya</p><p class="toggle2">Such interesting text, eh?</p><p class="toggle3">Another one</p>

莫回无

您可以通过使用只需修改代码的隐藏和显示功能来做到这一点。var isButtonClicked=[]$(document).ready(function(){&nbsp; $("p").hide();&nbsp; &nbsp;$("button").click(function(){&nbsp; &nbsp; &nbsp; var currentClass=$(this).attr("class");&nbsp; &nbsp; &nbsp; if($.inArray(currentClass,isButtonClicked)==-1)&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $("p").hide("slow");&nbsp; &nbsp; &nbsp; &nbsp; $("p."+currentClass).show("slow");&nbsp; &nbsp; &nbsp; &nbsp; isButtonClicked.push(currentClass);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;alert("second time you clicked")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$(this).hide()&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;})})<html><head>&nbsp; <meta charset="utf-8">&nbsp; <title>toggle demo</title>&nbsp; <style>&nbsp; &nbsp; p {&nbsp; &nbsp; &nbsp; background: #dad;&nbsp; &nbsp; &nbsp; font-weight: bold;&nbsp; &nbsp; &nbsp; font-size: 16px;&nbsp; &nbsp; }&nbsp; </style></head><body>&nbsp; <button class="toggle1">Toggle 1</button>&nbsp; <button class="toggle2">Toggle 2</button>&nbsp; <p class="toggle1">Hiya</p>&nbsp; <p class="toggle2">Such interesting text, eh?</p></body></html><script src="https://code.jquery.com/jquery-3.4.1.js"></script>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答