當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


jQuery event.target用法及代碼示例


jQuery event.target是一個內置屬性,用於查找哪個 DOM 元素將啟動該事件。

用法:

event.target

參數:它不接受任何參數,因為它是一個屬性,而不是一個函數。

示例 1:此示例顯示了 event.target 屬性的工作原理。

HTML


<!DOCTYPE html>
<html>
<head>
    <style>
        span,
        strong,
        p {
            padding: 8px;
            display: block;
            border: 2px solid green;
            width: 50%;
            margin: 10px;
        }
        #output {
            margin: 10px;
            padding: 10px;
            width: 100px;
            border: 2px solid green;
            display: block;
        }
    </style>
    <script src=
"https://code.jquery.com/jquery-1.10.2.js">
    </script>
</head>
<body>
    <div>
        <p>
            <strong><span>click Here !</span></strong>
        </p>
    </div>
    <!-- output will show inside this block -->
    <div id="output"></div>
    <!-- jQuery code to show working of this property -->
    <script>
        $("body").click(function (event) {
            $("#output").html("clicked: "
                + event.target.nodeName);
        });
    </script>
</body>
</html>

輸出:

示例 2:在此示例中,單擊任何 DOM 元素時都會彈出一個窗口。

HTML


<!DOCTYPE html>
<html>
<head>
    <style>
        span,
        strong,
        p {
            padding: 8px;
            display: block;
            border: 2px solid green;
            width: 50%;
            margin: 10px;
        }
    </style>
    <script src=
"https://code.jquery.com/jquery-1.10.2.js">
    </script>
</head>
<body>
    <center>
        <div>
            <p>
                <strong><span>click Here !</span></strong>
            </p>
        </div>
        <!-- jQuery code to show working of this property -->
        <script>
            $("body").click(function (event) {
                $("").html("clicked: " + event.target.nodeName);
                alert(event.target.nodeName + " is clicked");
            });
        </script>
    </center>
</body>
</html>

輸出:



相關用法


注:本文由純淨天空篩選整理自kundankumarjha大神的英文原創作品 jQuery event.target Property。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。