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


jQuery callbacks.fireWith()用法及代碼示例

jQuery中的callbacks.fireWith()方法用於使用給定的上下文和參數調用列表中當前存在的所有回調。

用法:

callbacks.fireWith([context][, params])

參數:

  • context:此參數定義對上下文的引用,在該上下文中應觸發列表中的回調。
  • params:此參數是要傳遞到列表中的回調的數組或參數的array-like對象。如果未使用或未定義,則不會傳遞任何參數。

返回值:此方法返回其附加到的回調對象。

範例1:本示例使用上下文‘window’並將參數傳遞給函數。



<!DOCTYPE HTML> 
<html> 
  
<head> 
    <script src= 
"https://code.jquery.com/jquery-3.5.0.js"> 
    </script> 
</head> 
  
<body style="text-align:center;"> 
    <h1 style="color:green;"> 
        GeeksForGeeks 
    </h1> 
      
    <p> 
        JQuery | callbacks.fireWith() method 
    </p> 
      
    <button onclick="Geeks();"> 
        click here 
    </button> 
      
    <p id="GFG_DOWN"></p> 
      
    <script> 
        var el_down = document.getElementById("GFG_DOWN"); 
  
        var res = ""; 
        var callbacks = jQuery.Callbacks(); 
  
        function Geeks() { 
  
            // First function to be added to the list 
            var func = function (val) { 
                res = res + "value passed is - " + val; 
            }; 
  
            // Add the function func to 
            // the callbacks list 
            callbacks.add(func); 
  
            // Fire the callbacks on the list 
            // using the context "window" 
            // and an parameters array 
            callbacks.fireWith(window, ["gfg_1"]); 
            el_down.innerHTML = res; 
        }  
    </script> 
</body> 
  
</html> 

輸出:

範例2:本示例使用上下文‘window’並將2參數傳遞給函數。

<!DOCTYPE HTML> 
<html> 
  
<head> 
    <script src= 
"https://code.jquery.com/jquery-3.5.0.js"> 
    </script> 
</head> 
  
<body style="text-align:center;"> 
  
    <h1 style="color:green;"> 
        GeeksForGeeks 
    </h1> 
      
    <p> 
        JQuery | callbacks.fireWith() method 
    </p> 
      
    <button onclick="Geeks();"> 
        click here 
    </button> 
      
    <p id="GFG_DOWN"></p> 
  
    <script> 
        var el_down = document.getElementById("GFG_DOWN"); 
        var res = ""; 
        var callbacks = jQuery.Callbacks(); 
  
        function Geeks() { 
  
            // first function to be added to the list 
            var func = function (val_1, val_2) { 
                res = res + "values passed are - " 
                        + val_1 + ", " + val_2; 
            }; 
  
            // Add the function func to 
            // the callbacks list 
            callbacks.add(func); 
  
            // Fire the callbacks on the 
            // list using the context "window" 
            // and an parameters array 
            callbacks.fireWith(window, ["gfg_1", "gfg_2"]); 
            el_down.innerHTML = res; 
        }  
    </script> 
</body> 
  
</html>

輸出:




相關用法


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