首页 > 解决方案 > 如何使用该 div id 内的按钮将“getelementbyid”值设置为 div id

问题描述

我有大约 300 个 div 的内容,我需要能够隐藏当前的 div 并在单击按钮时根据其 id 显示一个新的 div。大多数设置为一个接一个地流动,其中一些根据您单击的按钮循环回以前或将来的 div 标签。每个以前的 div 都需要隐藏,每个新的 div 都需要在点击时显示。我可以布置每个单独的函数,但我宁愿设置一个脚本或函数来设置 getelementbyid div id 隐藏和 div id 显示,以便它可以设置 onclick 并且我最终不会使用 300 多个函数

HTML 代码

<div id="myDIV" >
<p>Sample Text Goes Here</p>
<div>
<button type="button" onclick="myFunction(); myFunction2();">
Next</button>
</div>
</div>

<div id="myDIV2" style="display:none">
<p>Next sample Text Goes Here</p>
<div>
<button type="button" onclick="myFunction(); myFunction2();">
Back</button>
<button type="button" onclick="myFunction2(); myFunction3();">
Next</button>
</div>
</div>....

Javascript代码

function myFunction(){var x = document.getElementById("myDIV");
if (x.style.display === "none") {x.style.display = "block";} else {x.style.display = "none";}
}
function myFunction2() {var x = document.getElementById("myDIV2");
if (x.style.display === "none") {x.style.display = "block";} else {x.style.display = "none";}
}
function myFunction3() {var x = document.getElementById("myDIV3");
if (x.style.display === "none") {x.style.display = "block";} else {x.style.display = "none";}
} 
function myFunction4() {var x = document.getElementById("myDIV4");
if (x.style.display === "none") {x.style.display = "block";} else {x.style.display = "none";}
} 

为了清楚起见,这个脚本在我的 div 标签下,在页面的正文部分。非常感谢任何提示或帮助

标签: javascripthtmljquery

解决方案


只需将 div 的 id 作为参数传递

<div id="myDIV" >
     <p>Sample Text Goes Here</p>
     <div>
         <button type="button" onclick="myFunction('myDIV', 'myDIV2');">
         Next</button>
      </div>
</div>

//  1 method for all divs
function myFunction(currentID, nextID) {
    var  currentDIV = document.getElementById(currentID);
    var  nextDIV = document.getElementById(nextID);
    currentDIV.style.display = "none";
    nextDIV.style.display = "block";
}

推荐阅读