簡體   English   中英

JQuery 函數采用的一些參數

[英]JQuery some parameters that functions take

在 jQuery 中有一個我無法理解的例子。 在這段代碼中:

  $("#test1").text(function(i, origText){
    return "Old text: " + origText + " New text: Hello world!
    (index: " + i + ")";
  });
});

內置的.text() function 有 2 個參數:i,origText。 但這是我的問題,它們不是未定義的嗎?

jQuery怎么知道origText是原文,i是索引?

jQuery 文檔在這里這里解釋了它的含義。 基本上,它在被調用(觸發事件)時自動填充,並填充觸發它的元素的索引及其當前內容(文本)。

描述:將匹配元素集合中的每個元素的內容設置為指定的文本。

Function( Integer index, String text ) => String A function 返回要設置的文本內容。 接收集合中元素的索引 position 和舊文本值 arguments。

功能(索引,當前內容)可選。 指定返回所選元素的新文本內容的 function index - 返回集合中元素的索引 position currentcontent - 返回所選元素的當前內容

JavaScript 中的函數可以作為 arguments 傳遞。 這在任何語言中都不一樣,但因為函數在 JavaScript 中基本上是對象,所以它們可以。

您也可以這樣做,就像他們對 jQuery 所做的那樣。 創建一個 function ,它將 function 作為參數。 在 function 內部,使用自己的 arguments 調用參數 function,如下例所示,兩個 ZDBC11CAA5BDA9E7D77 中的字符串分別為 FBBD5BDA9E7D77666

您的其他函數(稱為回調函數)可以傳遞給第一個 function 並期望兩個字作為 arguments 傳遞。 您可以根據您想要對第一個 function 給您的輸入做什么來傳遞不同的回調函數。

 function exampleFunction(expectedFunction) { if (typeof expectedFunction === 'function') { expectedFunction('foo', 'bar'); } } function showWords(firstWord, secondWord) { console.log(firstWord, secondWord); } function combineWordsWithHyphen(firstWord, secondWord) { console.log(`${firstWord}-${secondWord}`); } exampleFunction(showWords); exampleFunction(combineWordsWithHyphen); exampleFunction(function(firstWord, secondWord) { console.log(secondWord, firstWord); });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM