oboer oboer - 1 month ago 12
jQuery Question

jQuery basics (theory) - what can I do with index (i) parameter in .text(i, x), .html(i, x) or .val(i, x)?

I'm going through jQuery tutorial on ws3school. I understand how it works, but I cannot think in what way it can be used.

Example from website below or here.



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

$("#btn2").click(function(){
$("#test2").html(function(i, origText){
return "Old html: " + origText + " New html: Hello <b>world!</b> (index: " + i + ")";
});
});
});

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>

<p id="test1">This is a <b>bold</b> paragraph.</p>
<p id="test2">This is another <b>bold</b> paragraph.</p>

<button id="btn1">Show Old/New Text</button>
<button id="btn2">Show Old/New HTML</button>

</body>
</html>





Anyone could give an example? Code appreciated, but not necessary.

Answer

You may need to use it in a case like this:

$( "ul li" ).text(function( index ) {
  return "item number " + ( index + 1 );
});

Which means .text(index) might be useful when you use it in arrays.