繁体   English   中英

通过单击按钮显示 Div,隐藏其他

[英]Show Div by clicking on button, hide others

我希望在单击“欧洲”按钮时显示 ID = '1' 的 div 容器的内容。 单击“美国”按钮时,应显示 id 为 2 的 DIV 的内容。

我的代码存在以下问题:我无法管理 select 页面加载时没有显示 DIV 或仅显示特定的 DIV。 第一次单击按钮后,function 不再起作用。

使用 www.DeepL.com/Translator 翻译(免费版)

 function showOne(id) { $('.hide').not('#' + id).hide(); }
 <button type="button" onclick="showOne('1')">Europe</button> <br> <button type="button" onclick="showOne('2')">USA</button> <div class='hide' id='2'>About USA</div> <div class='hide' id='1'>About Europe</div>

您只需要在单击按钮时首先显示当前 div,如下所示:

 function showOne(id) { $('#' + id).show(); $('.hide').not('#' + id).hide(); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button type="button" onclick="showOne('1')">Europe</button> <br> <button type="button" onclick="showOne('2')">USA</button> <div class='hide' id='2'>About USA</div> <div class='hide' id='1'>About Europe</div>

您可以尝试添加.show()方法以在隐藏之前显示所有元素:

 function showOne(id) { $('.hide').show().not('#' + id).hide(); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button type="button" onclick="showOne('1')">Europe</button> <br> <button type="button" onclick="showOne('2')">USA</button> <div class='hide' id='2'>About USA</div> <div class='hide' id='1'>About Europe</div>

老实说,这是一个非常简单的问题,我确信这些问题已经有了答案,无论如何,你可以这样做:

编辑

我可以补充一下,这个解决方案只包括 web 原生技术,没有包括 jQuery,我不确定这在你眼中是利还是弊。 无论如何,如果您想了解更多关于我使用过的原生 JavaScript 的信息,也许MDN会是一个很好的起点。

 function showOne(id) { document.querySelectorAll(".hide").forEach(function (el) { el.style = "display: block;"; }); document.querySelector(".hide[id='" + id + "']").style = "display: none;"; };
 .hide { display: none; }
 <button type="button" onclick="showOne('1')">Europe</button> <br> <button type="button" onclick="showOne('2')">USA</button> <div class='hide' id='1'>About USA</div> <div class='hide' id='2'>About Europe</div>

暂无
暂无

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

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