我有三个按钮和三个JS函数,可切换三个不同div的显示。如何将我的三个JS函数简化/压缩为一个将每个按钮连接到其相应内容的函数?

例:

HTML按钮

<button onclick="myFunction1()">Button 1</button>
<button onclick="myFunction2()">Button 2</button>
<button onclick="myFunction3()">Button 3</button>

HTML内容
<div id="ContentOne">This is Content One.</div>
<div id="ContentTwo">This is Content Two.</div>
<div id="ContentThree">This is Content Three.</div>

的JavaScript
function myFunction1() {
    var x = document.getElementById("ContentOne");
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}

function myFunction2() {
    var x = document.getElementById("ContentTwo");
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}

function myFunction3() {
    var x = document.getElementById("ContentThree");
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}

最佳答案

向压缩函数等添加参数!

function myFunction(id) {
  var x = document.getElementById(id);
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
<button onclick="myFunction('ContentOne')">Button 1</button>
<button onclick="myFunction('ContentTwo')">Button 2</button>
<button onclick="myFunction('ContentThree')">Button 3</button>

<div id="ContentOne">This is Content One.</div>
<div id="ContentTwo">This is Content Two.</div>
<div id="ContentThree">This is Content Three.</div>


说明

功能内唯一不同的部分是ID,因此请分离ID。该功能不需要知道哪个元素将受到样式匹配的影响。因此,请保留功能“转储”。

进一步学习:Anti-Patterns

如果您有兴趣改善编程风格,建议您看一下一些反模式。例如,您演示了hard coding的反模式。这并不像您想的那样不典型。

09-26 19:07
查看更多