首页 > 解决方案 > Javascript优化:重复相同的功能

问题描述

我想多次使用 getElemendbyId 函数,只需将 ID 的名称作为变量传递即可。

我想有一种更优雅的方法可以做到这一点:

<div id="1" onclick="myFunction2()"></div>
<div id="2" onclick="myFunction3()"></div>
<div id="3" onclick="myFunction4()"></div>
<div id="4" onclick="myFunction5()"></div>
<script>
function myFunction2() { document.getElementById("2").innerHTML = "test2"; }
function myFunction3() { document.getElementById("3").innerHTML = "test3"; }
function myFunction4() { document.getElementById("4").innerHTML = "test4"; }
</script>

谢谢!

标签: javascript

解决方案


<div id="1" onclick="myFunction(2, 'test2')"></div>
<div id="2" onclick="myFunction(3, 'test3')"></div>
<div id="3" onclick="myFunction(4, 'test4')"></div>
<div id="4" onclick="myFunction(5, 'test5')"></div>
<script>
    function myFunction(id, content) {
        document.getElementById(id).innerHTML = content; 
    }
</script>

推荐阅读