What are the two params in the function and how does this work?
I saw this in an application and it works well but i开发者_StackOverflow社区 dont understand how it works.... What is the function(i,text) part doing and what are they for
its being used here
$(this).text(function(i,text) { return (text == 'Show') ? 'Hide' : 'Show'; });
Certain jQuery methods let you pass a function in that manner. When you do, it iterates over the elements in the jQuery object.
In this case:
i
is the index of the current item in the settext
is the current text content value (before you modify it)
That is the pattern for most of the functions that have this capability.
Think of it like this:
$(this).each(function( i ) {
var i = i; // Redundant, I know.
var text = $(this).text();
$(this).text( (text == 'Show') ? 'Hide' : 'Show' );
});
EDIT:
I guess I should note that in your particular example, since there's only one element, it appears to be being used to prevent the need to explicitly call text()
twice in the handler, like this:
var $th = $(this);
$th.text(($th.text() == 'Show') ? 'Hide' : 'Show' );
I'm not sure which would perform better.
Checking the jQuery API: http://api.jquery.com/text/
the function is passed an index (i
) and the text (text
).
text()
would return the jQuery objects text value.
As a function is passed as a parameter that functions return value will be set as the jQuery objects text value.
So, the anonymous function is called with the current text value, checked if it is 'Show'
, and then set accordingly (by function return which is then passed to the text()
-fn).
精彩评论