ev.target: 表示当前按钮,其实就是事件的触发者,.addEventListener(事件名称, 回调方法, 传递机制/捕获/冒泡),false: 冒泡阶段触发这个事件, true: 捕获阶段。%s是占位符,
代码如下:
<html lang=""><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Document</title></head><body><!-- 这是直接添加事件属性的方式 --><button onclick="console.log(`哈哈,这是按钮一`)">按钮一</button><!-- 这是通过事件属性添加函数的方式 --><button onclick="hanshu(this)">按钮二</button><!-- 通过给对象添加属性的方式 --><button>按钮三</button><button>按钮四</button><script>// 这是按钮二的事件属性的函数function hanshu() {console.log("哈哈 这是按钮二");}const bt3 = document.querySelector("button:nth-of-type(3)");bt3.onclick = () => console.log("哈哈,这是按钮三");// 事件监听器const bt4 = document.querySelector("button:nth-of-type(4)");// .addEventListener(事件名称, 回调方法, 传递机制/捕获/冒泡)bt4.addEventListener("click", () => console.log("哈哈,这是按钮四的监听"), false);bt4.addEventListener("mouseover", () => console.log("移进来了"), false);bt4.addEventListener("mouseout", () => console.log("移出去了"), false);</script><ul><li>第一行</li><li>第二行</li><li>第三行</li><li>第四行</li><li>第五行</li></ul><script>// 根据冒泡原理,子元素的同名事件会向上冒泡到父级元素的同名事件上const ul = document.querySelector("ul");// ev.target: 事件的触发者, ev.currentTarget: 事件的绑定者ul.addEventListener("click", (aa) => console.log("触发 %s, 绑定 %s", aa.target, aa.currentTarget), false);</script></body></html>
截图在这
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号