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


JQuery bind()用法及代碼示例

jQuerybind()是一種內置方法,用於為選定元素附加一個或多個事件處理程序,此方法指定事件發生時要運行的函數。

用法:

$(selector).bind(event, data, function);

參數:

它接受下麵指定的三個參數 -

  • event:這是傳遞給所選元素的事件類型。
  • data:這是可以在所選元素上顯示的數據。
  • function:這是由所選元素執行的函數。

注意此方法已被棄用。

jQuery 代碼顯示 bind() 方法的用法原理:

示例 1:在下麵的代碼中,”click” 事件使用此方法附加到給定段落。

HTML


<!DOCTYPE html>
<html>
<head>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            $("p").bind("click", function () {
                alert("Given paragraph was clicked.");
            });
        });
    </script>
    <style>
        p {
            display: block;
            padding: 50px;
            width: 280px;
            border: 2px solid green;
        }
    </style>
</head>
<body>
    <p>Click me!</p>
</body>
</html>

輸出:

示例 2:在下麵的代碼中,添加了相同的 “click” 事件,但這次數據也傳遞給此方法。

HTML


<!DOCTYPE html>
<html>
   
<head>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
   
    <script>
        function handlerName(e) {
            alert(e.data.msg);
        }
        <!--Here data is passing along with a function in
            bind method-->
                $(document).ready(function () {
                    $("p").bind("click", {
                        msg: "You just clicked the paragraph!"
                    }, handlerName)
                });
    </script>
   
    <style>
        p {
            display: block;
            padding: 50px;
            width: 280px;
            border: 2px solid green;
        }
    </style>
</head>
   
<body>
    <!--A pop will appear after clicking 
        on this paragraph-->
    <p>Click me!</p>
</body>
   
</html>

輸出:



相關用法


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