将点击事件动态添加到按钮

时间:2019-11-27 08:40:02

标签: javascript html css

我正在尝试将点击事件动态添加到按钮上。问题是该功能在我单击按钮之前就已触发 这是我的代码..

<!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 个答案:

答案 0 :(得分:0)

您可以在匿名函数内部调用该函数:

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>