[英]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 的情况下切换隐藏类,将有多个商店,所以我试图创建一个可以工作的函数为他们所有人而不是为每个人创建一个单独的函数。
我以为我可以做类似的事情:
function showShop(id) {
const elem = document.getElementById(id);
alert(id);
const div = elem.closest('div');
div.classList.toggle('hidden');
}
但它引用的是页面上的第一个 div 而不是按钮后的第一个 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
,因为它们很难跟踪。 相反,您应该相对于单击的按钮进行导航。 下面是一个脚本,无需使用任何id
即可轻松处理多个商店部分:
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
事件监听器的时候。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.