<div onclick="test()"></div> <script> function test(){ //code } </script>
上面这种方法是很low逼的,用了这种方法工资就涨不上去你信不信?下面这种也是...
<div id="test"></div> <script> var test = document.getElementById("test"); test.onclick = function(){ //code }; </script>
能不能用一个稍微有点逼格的方法?
<div id="test"></div> <script> var test = document.getElementById("test"); test.addEventListener("click",function(){ //code }); </script>
addEventListener() 还能解绑
<div id="test"></div> <script> var test = document.getElementById("test"); function testFunction(){ //code } test.addEventListener("click",testFunction); test.removeEventListener("click",testFunction); </script>
听说这个方法对IE8无法向下兼容?没关系,我们还有attachEvent/detachEvent
<div id="test"></div> <script> var test = document.getElementById("test"); function testFunction(){ //code } //绑定 if (test.addEventListener) { test.addEventListener("click", testFunction); } else if (test.attachEvent) { test.attachEvent("onclick", testFunction); } //解除 if (test.removeEventListener) { test.removeEventListener("click", testFunction); } else if (test.detachEvent) { test.detachEvent("onclick", testFunction); } </script>
时间: 2024-10-25 17:59:42