使用addEventListener绑定点击事件替代onclick的问题排查
代码核心错误
- JS代码未包裹在
<script>标签中,浏览器无法识别执行 addEventListener的第二个参数错误传入了执行后的函数:你写的getAttributes()带括号会立刻执行函数,而非将函数作为事件回调绑定,正确写法是传入不带括号的函数引用getAttributes- 事件绑定逻辑位置错误:你把事件绑定代码放在了
getAttributes函数内部,只有函数被执行时才会触发绑定,逻辑完全颠倒 - 事件绑定对象与需求不符:你绑定的是
<p>标签的点击事件,实际需求是点击按钮触发逻辑,应该绑定到按钮元素上
修正后代码
<!DOCTYPE html> <html> <body> <p><a id="w3r" type="text/html" hreflang="en-us" rel="nofollow" target="_self" href="https://www.w3resource.com/">w3resource</a></p> <!-- 给按钮添加id方便选中 --> <button id="attrBtn">Click here to get attributes value</button> <script> function getAttributes() { var v = document.getElementById('w3r').href ; alert('the value of the attribute is : '+v); var w = document.getElementById('w3r').hreflang; alert('the value of the attribute is : '+w); var x = document.getElementById('w3r').rel; alert('the value of the attribute is : '+x); var y = document.getElementById('w3r').target; alert('the value of the attribute is : '+y); var z = document.getElementById('w3r').type; alert('the value of the attribute is : '+z); } // 页面DOM加载完成后绑定按钮点击事件 document.addEventListener('DOMContentLoaded', function() { document.getElementById('attrBtn').addEventListener('click', getAttributes); }) </script> </body> </html>
内容的提问来源于stack exchange,提问作者user16224243
相关产品推荐
相关产品推荐

