在 jQuery 中,jQuery.bind() 和 jQuery.live() 方法有什麼區別?


jQuery.bind() 方法

jQuery 中的 bind() 方法用於為選定的元素附加一個或多個事件處理程式。
注意:jQuery bind() 方法在 jQuery 中已棄用。

示例

您可以嘗試執行以下程式碼,學習如何在 jQuery 中使用 bind() 方法。

線上演示

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("div").bind("click", function(){
        alert("Hello World!");
    });
});
</script>
</head>
<body>

<div>Click me! I am an alert!</div>

</body>
</html>

jQuery.live() 方法

live( type, fn ) 方法將事件處理程式繫結到所有當前和未來匹配元素的事件(如 click)。它還可以繫結自定義事件。

以下是此方法使用所有引數的描述

  • type:事件型別。
  • fn:一個函式,繫結到匹配元素集中的每個元素上的事件。

示例

您可以嘗試執行以下程式碼,學習如何使用 live() 方法。

注意:live() 方法在 jQuery 1.7 中已棄用,並在 1.9 版本中移除。因此,如果您想執行 live() 方法,請使用以下程式碼中低於 1.7 版本的 jQuery。

線上演示

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js">
</script>
<script>
$(document).ready(function() {
    $("button").live("click", function() {
        $("p").slideToggle();
    });
});
</script>
</head>
<body>
<p>This is demo text.</p>
<p>This is another text.</p>
<button>Click to toggle</button>
<br><br>
<div>The live() method deprecated in jQuery 1.7, and removed in version 1.9. So, if you want to run the live() method</div>
</body>
</html>

更新於: 2019-12-09

161 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.