jQuery $.each 循环中的 'each' 是什么?

What is 'each' in the jQuery $.each looping?

我正在尝试访问 table 行中的数据。数据可能位于 <td> 标签中,或作为输入中的文本,或作为输入中的复选框或按钮。

作为演示,我有一个小 table:-

<table border="1">
  <tr>
    <td dir="ltr" id="test1" class="tLine" nowrap>Column One</td>
    <td><input type="checkbox" name="vehicle" value="Car" checked>Check Box.</td>
    <td>
      <button type="button" class="clicked">Update</button>
    </td>
  </tr>
</table>    

Javascript 是:-

<script>
    $(".clicked").click(function() {
        var $row = $(this).closest("tr");       // Finds the closest row <tr> 
        var $tds = $row.find("td");             // Finds all children <td> elements
        $.each($tds, function() {               // Visits every single <td> element
           console.log($(this).text());        // Prints out the text within the <td>
         });
        console.log($tds[0].tagName); // 'TD'
        console.log($tds[1].tagName); // 'TD'
        $.each($tds, function(index, value) { // Visits every single <td> element
           console.log($tds[index].tagName); // 'TD'
           console.log($(this).tagName);  // Undefined
           console.log($(each).tagName);  // Fails
         });
    });
</script>

第二个循环中的 each 到底是什么?我该如何使用它? 为什么 $(this).tagName 未定义?

获得 TD 元素后,我可以通过查看子项来检查内容是什么...

我也在查看 javascript/jquery table 选项,如 SlickGred、jsgrid 和 DataTables,但想先了解上面的代码。

$(this) returns 一个 jQuery 对象。 thisDOMElement.

What exactly is the each in the 2nd loop and how do I use it?

如果您指的是集合中的一个元素,它是 value,您的回调函数中的第二个参数。但是使用 $.each 你也可以使用 this.

Why is the $(this).tagName undefined?

因为$(this)实例化了一个jQuery对象,而jQuery对象中没有tagName属性。你可以做 this.tagName,或 value.tagName.

$tds[0].tagName 起作用的原因是虽然 $tds 是一个 jQuery 对象,但它也是一个 "array-like" 对象,因为所有包含在它像 '0''1' 等一样被放置在 properties/indices 中。所以当您执行 $tds[0] 时,您会得到实际的元素并且它具有 tagName 属性.