...

View Full Version : function return



minkoko
09-21-2011, 05:30 PM
hi,i don't understand about the jquery basic example
the code is below

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$('p').addClass(function(n){
return 'par_' + n;
});
});
});
</script>
<style type="text/css">
.par_0
{
color:blue;
}
.par_1
{
color:red;
}
</style>
</head>

<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Add classes to p elements</button>
</body>
</html>



i want to understand about the how is work function(n){ in the function a
and how work return function return 'par_' + n;
thanks mate

devnull69
09-21-2011, 07:10 PM
This is one of the possible ways to use the addClass method: The first parameter of the function "n" is the index of the current element out of the jQuery element list

Let's say you have 10 <p> paragraphs on your page. Then the selector $('p') will result in a list of those paragraphs. addClass(function(n) {...}) will then add a class to each paragraph containing the text par_n. So the first paragraph will have a new class="par_0"

rnd me
09-21-2011, 10:33 PM
i guess mopst methods map to .map(), which i didn't know.
so, the long-hand would be:


$('p').map(function(n, elm){
$(elm).addClass('par_' + n);
});

minkoko
09-22-2011, 01:29 PM
thanks for explain my dearly friend,



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum