jQuery 事件 $.proxy() 方法



jQuery 事件$.proxy()方法允許您建立一個具有特定上下文(即其值)的新函式。這對於將事件處理程式繫結到上下文需要指向不同物件的元素很有用。

$.proxy() 方法在 jQuery 3.3 版本中已棄用。

語法

以下是 jQuery 事件$.proxy(()方法的語法:

$(selector).proxy(function, context)

引數

該方法接受兩個名為“function”和“context”的引數。這些引數描述如下:

  • function - 將更改其上下文的現有函式。
  • context - 函式上下文應設定為的物件。

返回值

此方法不返回值。

示例 1

以下是 jQuery 事件$.proxy()方法的基本示例:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
    <p>Click on the below button to set the context of the details function inside studentDetails.</p>
    <button>Click me</button>
    <br><br>
    <span></span>
    <script>
        var studentDetails = {
            details: function() {
                $('span').text("Student details: Name, age, city, etc.");
            }}
            $("button").click($.proxy(studentDetails, "details"));
    </script>
</body>
</html>

輸出

執行上述程式後,將顯示一個按鈕。單擊時,它將在“studentDetails”物件中設定“details”函式的上下文:


示例 2

以下是 jQuery 事件$.proxy(()方法的另一個示例。我們使用此方法將函式的上下文更改為特定物件:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
    <p>The pop-up alert "Hello TutorialsPoint" will appear on the browser screen every 2 seconds.</p>
    <script>
        var obj = {
            name: "TutorialsPoint",
            sayHello: function(){
                alert("Hello " + this.name);
            }
        };
        //setInterval(obj.sayHello, 2000); it will display only "Hello" + undefined.
        setInterval($.proxy(obj.sayHello, obj), 2000);
    </script>
</body>
</html>

輸出

上面的程式每兩秒顯示一個包含指定內容的彈出警報:


jquery_ref_events.htm
廣告

© . All rights reserved.