猿问

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

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


<!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>


慕侠2389804
浏览 104回答 1
1回答

Helenr

您可以在匿名函数内部调用该函数:b.addEventListener("click", function() {colorIt(p)} );function start() {&nbsp; var p = document.getElementById("myP");&nbsp; var b = document.getElementById("myB");&nbsp; b.addEventListener("click", function() {colorIt(p)} );}function colorIt(ele){&nbsp; ele.setAttribute("style", "color : red" );}window.addEventListener("load", start , false);<button id="myB"> click me </button><p id ="myP"> test </p>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答