Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85575

how parameter inside function works?

html

<p>This is a <b>bold</b> paragraph.</p>
<button>Add</button>

jquery

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

I would like to know origText is not called outside function but it is returning the value. How?

demo

Upvotes: 4

Views: 2630

Answers (4)

Navin Rauniyar
Navin Rauniyar

Reputation: 10535

In simple:

text(function(whatever){
      return whatever; // returns the text what is the text it has.
    });

In your example p has text : This is a bold paragraph.

return whatever will return your text : This is a bold paragraph.

Upvotes: 0

Tommi
Tommi

Reputation: 3247

Function text does some preparations about input nodes and then runs callback provided by user (your function), and it pass to your callback this two arguments (which prepared on "some preparations") step. If you want exact code, you can read jQuery source.

Upvotes: 0

Plymouth223
Plymouth223

Reputation: 1925

The actual method text takes a function as a parameter. The function passed to text may contain two parameters, the first of which receives the index, the second the original text.

Upvotes: 2

Suresh Atta
Suresh Atta

Reputation: 122008

As docs says

function(index, text)

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.

And How does jQuery’s .text() work, internally?

Upvotes: 2

Related Questions