javascript - 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>
谢谢!
解决方案
<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>
推荐阅读
- .net - 发现同一依赖程序集的不同版本之间存在冲突 - app.config 与 packages.config 不同
- security - 这种反机器人防御是如何工作的?
- c# - SQL 查询返回空值
- python - 将用户模型调用到序列化程序后,Django rest 框架未登录非超级用户
- android-studio - 为什么 Android Studio 3.1.3 和/或模拟器会启动数百个 adb 实例?
- r - 通过对数据进行分组并选择列的最小值来过滤列并创建新列
- javascript - 在 npm 请求函数之外获取值
- java - 在java中映射数组列表
- perl - Perl 获取哈希值中的哈希值
- php - 在php中刷新后保留输入值