jQuery eachメソッドにindexを指定してリスト要素のインデックスを取得

環境
Google Chrome 106.0.5249.119
Windows 10 Home 64bit
jQuery 3.6.0

構文
$('リストのセレクター名 li’).each(function(index) {繰り返し処理コード
eachメソッドの引数1はindexを指定します。
indexを使ってリスト要素のインデックス値を取得します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#btnadd').click(function(){
$('.cft li').each(function(index) {
  // indexの取得
$(this).text(index);
});
});
});
</script>
</head>
<body>
<ul class="cft">
<li>tokyo</li>
<li>oosaka</li>
</ul>
<button id="btnadd">実行</button>
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(document).ready(function(){ $('#btnadd').click(function(){ $('.cft li').each(function(index) {   // indexの取得 $(this).text(index); }); }); }); </script> </head> <body> <ul class="cft"> <li>tokyo</li> <li>oosaka</li> </ul> <button id="btnadd">実行</button> </body> </html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $('#btnadd').click(function(){
    $('.cft li').each(function(index) {
      // indexの取得
        $(this).text(index);
    });
});
});
</script>
</head>
<body>
<ul class="cft">
  <li>tokyo</li>
  <li>oosaka</li>
</ul>
<button id="btnadd">実行</button>
</body>
</html>

結果
「実行」をクリックすると、「0」、「1」が表示されます。

jQuery

Posted by arkgame