简体   繁体   中英

JQuery some parameters that functions take

there's an example that I couldn't understand in jQuery. Here in this code:

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

the built in.text() function got 2 parameters: i, origText. But here's my problem, aren't they undefined?

How does jQuery knows that origText is the original text and i is the index?

jQuery documentation explains you what it means here and here . Basically, it is populated automatically when it is called (event is triggered) and it fills in the index of element for which it is triggered and its current content (text).

Description: Set the content of each element in the set of matched elements to the specified text.

Function( Integer index, String text ) => String A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments.

function(index,currentcontent) Optional. Specifies a function that returns the new text content for the selected elements index - Returns the index position of the element in the set currentcontent - Returns current content of selected elements

Functions in JavaScript can be passed as arguments. This is not the same in any language, but because functions are basically objects in JavaScript, they can.

You can do this too, like they did with jQuery. Create a function which takes in a function as an argument. Inside the function call the argument function with its own arguments, like in the example below, two arguments with strings in them.

Your other functions, which are called callback functions can be passed to the first function and expect two words being passed as arguments. And you can pass different callback functions based on what you want to do with the input the first function gives you.

 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); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM