target 事件属性可返回事件的目标节点(哪个 DOM 元素触发了该事件),如生成事件的元素、文档或窗口。
语法:event.target
<html> <head> <meta charset="UTF-8"> <script type="text/javascript" src="jquery/jquery-3.2.1.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $("button").click(function (event) { //返回的是大写的元素名BUTTON var targetNodeName = event.target.nodeName; //targetNodeName就是个字符串类型的元素名 if (typeof targetNodeName == "string") { //打印 alert("targetNodeName string") } $("div").html("点击事件由 " + targetNodeName + " 元素触发"); //$(targetNodeName)选择这个元素 if ($(targetNodeName).hasClass("button-class")) { //打印 alert("targetNodeName has class button-class") } var parentNode = $(event.target.nodeName).parent()[0].nodeName.toLowerCase(); //parentNode:body alert("parentNode:" + parentNode); }); }); </script> </head> <body> <button class="button-class">这是一个按钮</button> <div></div> </body> </html>
时间: 2024-10-10 02:49:15