跳过 jQuery 中 $.each 的最后一个索引

skip last index of $.each in jquery

本文关键字:最后一个 索引 each jQuery 跳过      更新时间:2023-09-26

http://jsfiddle.net/jxzwy4d6/

<tr>
    <td>abc</td>
    <td>Education</td>
    <td>abc customer</td>
    <td>123</td>
    <td>abc@gmail.com</td>
    <td>
        <button class="edit_record">Edit</button>
    </td>
</tr>

我的简斯

$(function () {
    $('body').on('click', '.edit_record', function (e) {
        $.each($(this).closest('tr'), function (i, obj) {
            //get all td text except last one

        });
    });
});

我试过了

if(i != 5){console.log($(this).find('td').text());}但它不起作用,则包含最后一个编辑值。

试试这个

$.each($(this).closest('tr').find('td').not(':last'), function (i, obj) {
    //get all td text except last one
     console.log($(this).html());
});

另一种方法是针对按钮父级的兄弟姐妹...无需以这种方式对索引大惊小怪

$('body').on('click', '.edit_record', function (e) {
    $(this).parent().siblings().each(function(){
         console.log( $(this).text() );
     });
});

参考兄弟姐妹((文档

您的代码永远不会到达索引 5,因为您遍历了 tr 元素。不是它的td元素,因为表行仅存在 1 个元素,请使用以下代码:

$.each($(this).closest('tr').find('td'), function(i, obj) {
 // i right now having value 0 - 5(this is your last index)
});

更新的演示

您可以使用.parent(), .parent('td') or .closest('td') 获取按钮的父级并查找.siblings,这将是所有td,但包含按钮的那个。而且,您可以使用.each()而不是jQuery.each()

  $(this).closest('td').siblings().each(function(i, td) {
      //The last td is excluded here as only the siblings are iterated.
  });

$(function() {
  $(document).on('click', '.edit_record', function() {
      $(this).closest('td').siblings().each(function(i, td) {
          console.log( td );
      });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table><tbody>
  <tr>
    <td>abc</td>
    <td>Education</td>
    <td>abc customer</td>
    <td>123</td>
    <td>abc@gmail.com</td>
    <td>
        <button class="edit_record">Edit</button>
    </td>
</tr>
  </tbody></table>

小提琴

$(document).on('click', '.edit_record', function() {   
    var table =$(this).closest('tr').find('td:not(:last)');
    table.each(function () {
        console.log($(this).text());
    });
});

你可以这样做。选择除最后一个 td 之外的所有 td,然后迭代所选 td 并获取其各自的文本