Reputation: 85575
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?
Upvotes: 4
Views: 2630
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
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
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
Reputation: 122008
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