所以我有我的网站的代码,我建立了自己,工作正常。问题是,我希望JavaScript代码更“干净”。我读到JavaScript是关于不重写代码的。问题是我不知道如何通过dropDownSeven函数重构dropDownOne。 每个功能对应一个特定的按钮,点击后会通过应用“show”类来显示相应的信息块,该类只显示一个属性:Display:block;如何重写这段代码?
所以要包装起来:我怎样才能重写代码,这样我只需要说一个函数就可以点击所有的按钮。如果点击某个按钮,该按钮内容应该显示,而不是其他按钮。
-No jQuery-
HTML:
<div class="dropdown">
<button onclick="dropDownFour()" class="projectbuttons">
PSD to Bussiness Site (01-2017)
</button>
<div id="dropdownfour" class="dropdown-content">
<!--Content-->
</div>
</div>
的JavaScript:
function dropDownOne() {
document.getElementById("dropdownone").classList.toggle("show");
}
function dropDownTwo() {
document.getElementById("dropdowntwo").classList.toggle("show");
}
function dropDownThree() {
document.getElementById("dropdownthree").classList.toggle("show");
}
function dropDownFour() {
document.getElementById("dropdownfour").classList.toggle("show");
}
function dropDownFive() {
document.getElementById("dropdownfive").classList.toggle("show");
}
function dropDownSix() {
document.getElementById("dropdownsix").classList.toggle("show");
}
function dropDownSeven() {
document.getElementById("dropdownseven").classList.toggle("show");
}
window.onclick = function (event) {
if (!event.target.matches('.aboutmebuttons, .projectbuttons,
#mailopenbutton, [name="name"],
[name="message"], ' + '[name="email"],
[name="submitmail"], [name="reset"],
#dropdownseven, #mailform')
) {
var dropDowns = document.getElementsByClassName("dropdown-content");
for (var i = 0; i < dropDowns.length; i++) {
var openDropDown = dropDowns[i];
if (openDropDown.classList.contains('show')) {
openDropDown.classList.remove('show');
}
}
}
}
谢谢!
戴上ID在一个数组,循环的,保持一个共同的功能并将值传递给循环中的该函数。 –
这应该在http:// codereview。stackexchange.com/ –