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

Show Div by clicking on button, hide others

我希望在单击 "Europe" 按钮时显示 ID = '1' 的 div 容器的内容。 单击按钮 "USA" 时,应显示 ID 为 2 的 DIV 的内容。

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

用 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>