单击按钮后获取第一个 div

Get first div after button is clicked

我有以下关于商店信息的信息:

<h3 class="-center"><shop>Shop name</shop></h3>
<button type="button" id="banff" onclick="showShop(this.id)"><shop-title><b>Bakery Shop</b></shop-title></button>
<p class="move-right"><shop-info>Shop Address · Shop number</shop-info></p>
  <div id="shop"  class="hidden">
    <p><shop-info>Opening soon</shop-info></p>
  </div>

我想要做的是,一旦点击按钮,它将在按钮之后获得第一个 div 并在不引用 id 的情况下切换隐藏的 class,将会有多家商店,所以我试图创建一个适用于所有商店的功能,而不是为每个商店创建一个 individual 功能。

我想我可以做类似的事情:

function showShop(id) {
const elem = document.getElementById(id);
 alert(id);
const div = elem.closest('div');
div.classList.toggle('hidden'); 

}

但是它引用了页面上的第一个 div 而不是按钮之后的第一个,我哪里出错了?或者我需要换一种方式吗?

提前感谢您的任何建议

将按钮 ID 与 div ID 连接起来如何?

类似于:

  <h3 class="-center"><shop>Shop name</shop></h3>
  <button type="button" id="button-1" onclick="showShop(this.id)">
    <shop-title><b>Bakery Shop</b></shop-title>
  </button>
  <p class="move-right"><shop-info>Shop Address · Shop number</shop-info></p>
  <div id="shop-button-1" class="hidden">
   <p><shop-info>Opening soon</shop-info></p>
  </div>

并且在 javascript 中的代码可以简化为:

function showShop(id) {
  const elem = document.getElementById(id);
  const div = document.getElementById('shop-' + id);

  div.classList.toggle('hidden'); 
}

您应该尽量避免使用 id,因为它们很难跟踪。相反,您应该相对于单击的按钮进行导航。下面是一个脚本,无需使用任何 ids:

即可轻松处理多个商店部分

document.querySelectorAll("button").forEach(btn=>{
  for(var div=btn;div=div.nextElementSibling;)
    if(div.tagName==="DIV") break;
  if(div) btn.onclick=()=>div.classList.toggle("hidden")
})
.hidden {display:none}
<h3 class="-center"><shop>Shop name</shop></h3>
<button><shop-title><b>Bakery Shop</b></shop-title></button>
<p class="move-right"><shop-info>Shop Address · Shop number</shop-info></p>
  <div class="hidden">Info on bakery shop:
<p><shop-info>Opening soon</shop-info></p>
  </div>
<button><shop-title><b>Iron Monger</b></shop-title></button>
<p class="move-right"><shop-info>Shop Address · Shop number</shop-info></p>
  <div class="hidden">Info on iron monger's:
<p><shop-info>already open!</shop-info></p>
  </div>
<button><shop-title><b>Fish Monger</b></shop-title></button>
<p class="move-right"><shop-info>Shop Address · Shop number</shop-info></p>
  <div class="hidden">Info on fish monger's:
<p><shop-info>will never open!</shop-info></p>
  </div>

在我最近的更新中,我再次调整了代码片段,这样我现在就可以进行“相关 <div> 的相对导航”仅一次:当时我定义并添加 onclick 事件监听器。