gpt4 book ai didi

JavaScript 在按钮点击时显示/隐藏 div - 每页多个

转载 作者:行者123 更新时间:2023-12-04 07:18:38 24 4
gpt4 key购买 nike

我正在尝试开发一个页面,其中会有多个 div,这些 div 中的每一个都有一个按钮,单击时会在其下方显示“下拉”样式的 div。
目前我有一些代码,当单击一个按钮时,它会在页面上显示所有“下拉”样式的 div,而不仅仅是与按钮位于同一容器中的那个。
我希望这在没有 jquery 的纯 JavaScript 中完成,任何帮助将不胜感激,谢谢!
HTML

<div class="fullResultsContainer">
<div class="resultContainer">
<div class="resultRow">
<!-- This has multiple divs but this is the only one relevant to the issue-->
<div class="resultMenu">
<button class="mobileShowActivityFeedBtn" onclick="mobileActivityLog()"> Show activity feed </button>
</div>
</div>

<div class="mobileDropDown">
<p> This is the content I want to show on button click</p>
</div>
</div>

<div class="resultContainer">
<div class="resultRow">
<!-- This has multiple divs but this is the only one relevant to the issue-->
<div class="resultMenu">
<button class="mobileShowActivityFeedBtn" onclick="mobileActivityLog()"> Show activity feed </button>
</div>
</div>

<div class="mobileDropDown">
<p> This is the content I want to show on button click</p>
</div>
</div>
</div>
JS
function mobileActivityLog() {
var btn = document.getElementsByClassName("mobileShowActivityFeedBtn");
var activity = document.getElementsByClassName("mobileDropDown");

for(var i=0; i<btn.length; i++) {
for(var j=0; i<activity.length; j++) {
if(activity[j].style.display == "none") {
activity[j].style.display = "flex"
} else {
activity[j].style.display = "none"
}
}
}
}

最佳答案

我认为最简单的方法是向方法和 getElementById 发送一个参数带有参数的连接字符串。

<div class="fullResultsContainer">
<div class="resultContainer">
<div class="resultRow">
<div class="resultMenu">
<button onclick="mobileActivityLog(1)"> Show activity feed </button>
</div>
</div>

<div class="mobileDropDown-1">
<p> This is the content I want to show on button click</p>
</div>
</div>

<div class="resultContainer">
<div class="resultRow">
<div class="resultMenu">
<button onclick="mobileActivityLog(2)"> Show activity feed </button>
</div>
</div>

<div id="mobileDropDown-2">
<p> This is the content I want to show on button click</p>
</div>
</div>
</div>
JS
function mobileActivityLog(index) {
var activity = document.getElementsById("mobileDropDown-" + index);
if(activity.style.display == "none") {
activity.style.display = "flex"
} else {
activity.style.display = "none"
}
}

关于JavaScript 在按钮点击时显示/隐藏 div - 每页多个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68636360/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com