我正在尝试将点击事件动态添加到按钮。问题是在我单击按钮之前触发了该功能这是我的代码..<!DOCTYPE html><html><head><title></title><script type="text/javascript"> function start() { var p = document.getElementById("myP"); var b = document.getElementById("myB"); b.addEventListener("click", colorIt(p) ); } function colorIt(ele){ ele.setAttribute("style", "color : red" ); } window.addEventListener("load", start , false);</script></head><body><button id="myB"> click me </button><p id ="myP"> test </p></body></html>
1 回答
Helenr
TA贡献1780条经验 获得超4个赞
您可以在匿名函数内部调用该函数:
b.addEventListener("click", function() {colorIt(p)} );
function start() {
var p = document.getElementById("myP");
var b = document.getElementById("myB");
b.addEventListener("click", function() {colorIt(p)} );
}
function colorIt(ele){
ele.setAttribute("style", "color : red" );
}
window.addEventListener("load", start , false);
<button id="myB"> click me </button>
<p id ="myP"> test </p>
添加回答
举报
0/150
提交
取消