如何只返回表中的第一个元素?(JavaScript)

我使用以下代码来获取选择的表行的信息,如何访问第一个元素(在本例中为 2)并将其分配给变量?


$(document).ready(function(){

$("#usersTable tr").click(function(){

    $(this).find("td").each(function(){

        console.log($(this).html());

    });

  });

})

它在控制台中返回以下内容

https://img1.sycdn.imooc.com/6576c2cf0001e00502620157.jpg

HTML 代码:


<table id="usersTable">

 <div id="div2">

 <tbody id="tableBody">

 <tr id="tableHeadings">

     <th>User ID</th>

     <th>Email</th>

     <th>Forename</th>

     <th>Surname</th>

     <th>Avatar</th>

 </tr>



 <tr id="row0">

     <td id="id0" title="User ID Number"></td>

     <td id="email0" title="User Email"></td>

     <td id="forename0" title="User Forename"></td>

     <td id="surname0" title="User Surname"></td>

     <td>

         <img id="image0"  title="User Image">

     </td>

 </tr>

</tbody>

</div>

</table>


RISEBY
浏览 133回答 3
3回答

料青山看我应如是

您可以使用函数index的参数each。&nbsp;https://api.jquery.com/each/$(document).ready(function(){$("#usersTable tr").click(function(){&nbsp; &nbsp; $(this).find("td").each(function(index){&nbsp; &nbsp; &nbsp; &nbsp; if (index === 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;console.log($(this).html());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; });&nbsp; });})如果您不需要其他td元素,请不要循环!最好使用下面这个解决方案。

慕田峪7331174

您可以使用这样的选择器,这样您就不必循环选定行的所有单元格$(document).ready(function() {&nbsp; $("#usersTable tr").click(function() {&nbsp; &nbsp; console.log($(this).find("td:first-child").html());&nbsp; });});

慕桂英546537

我已经重构了您的 HTML 结构并更新了 javascript 代码。$(document).ready(function() {&nbsp; $('tbody tr').on('click', function() {&nbsp; &nbsp; let firstTd = $(this).find('td:first-child');&nbsp; &nbsp; let userId = firstTd.text();&nbsp; &nbsp; console.log(userId);&nbsp; });});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><table id="usersTable">&nbsp; <div id="div2">&nbsp; &nbsp; &nbsp;<thead>&nbsp; &nbsp; &nbsp; &nbsp;<tr id="tableHeadings">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<th>User ID</th>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<th>Email</th>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<th>Forename</th>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<th>Surname</th>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<th>Avatar</th>&nbsp; &nbsp; &nbsp; &nbsp;</tr>&nbsp; &nbsp; &nbsp;</thead>&nbsp; &nbsp; &nbsp;<tbody id="tableBody">&nbsp; &nbsp; &nbsp; &nbsp;<tr id="row0">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<td id="id0" title="User ID Number">2</td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<td id="email0" title="User Email">some@e.com</td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<td id="forename0" title="User Forename">demo</td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<td id="surname0" title="User Surname">doe</td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<td>img</td>&nbsp; &nbsp; &nbsp; &nbsp;</tr>&nbsp; &nbsp; </tbody>&nbsp; </div></table>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5