我创建了4个按钮,每个按钮都有自己的ID,并且我有一个显示给定元素ID的函数。所以我想将其应用于所有这四个按钮。我做错了什么?
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button id='b1'>Click</button>
<button id='b2'>Click</button>
<button id='b3'>Click</button>
<button id='b4'>Click</button>
<script type="text/javascript">
function show_id(element){
alert(element.id)
}
for(i=0; i!=document.getElementsByTagName('button');i++){
target = document.getElementsByTagName('button')[i]
target.onclick = show_id(target)
}
</script>
</body>
</html>
如下所示-
function show_id() {
alert(this.id)
}
var buttons = document.querySelectorAll("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].onclick = show_id;
}
<button id='b1'>Click</button>
<button id='b2'>Click</button>
<button id='b3'>Click</button>
<button id='b4'>Click</button>
将参数传递给onclick事件-
使用HTML
-
function show(element, value) {
console.log(element.id);
console.log(value);
}
<button id='b1' onclick='show(this, "a")'>Click</button>
使用JS
-
function show(value, event) {
console.log(value);
console.log(event.target.id);
}
var button = document.getElementById("b1");
button.onclick = show.bind(this, "a");
<button id='b1'>Click</button>
但是,正如@connexo所述,用于addEventListener
绑定DOM事件。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句