如何仅返回表中的第一个元素?(JavaScript)
我使用下面的代码来获取选择表行的信息,在这种情况下,我如何访问第一个元素2并将其分配给变量如何仅返回表中的第一个元素?(JavaScript),javascript,html,Javascript,Html,我使用下面的代码来获取选择表行的信息,在这种情况下,我如何访问第一个元素2并将其分配给变量 $(document).ready(function(){ $("#usersTable tr").click(function(){ $(this).find("td").each(function(){ console.log($(this).html()); }); }); }) 它在控制台中返回以下内容 HTML代码: <table id="usersT
$(document).ready(function(){
$("#usersTable tr").click(function(){
$(this).find("td").each(function(){
console.log($(this).html());
});
});
})
它在控制台中返回以下内容
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>
您可以使用每个函数的索引参数。
如果你不需要其他td元素,不要循环!更好地使用下面的解决方案。我已经重新构造了您的HTML结构并更新了javascript代码 $document.readyfunction{ $'tbody tr'。单击,函数{ 让firstTd=$this.find'td:first child'; 让userId=firstTd.text; console.loguserId; }; }; 用户ID 电子邮件 名字 姓 阿凡达 2. some@e.com 演示 雌鹿 img
可以使用这样的选择器,这样可以避免循环选定行的所有单元格 $document.readyfunction{ $usersTable tr.clickfunction{ console.log$this.findtd:first-child.html; }; };
$this.findtd[0]正在工作?请共享HTML语法。this.querySelectortd。innerText@SajeebAhamed刚刚编辑了我的post@Shubham很遗憾,我把你给的索引改成了0,效果很好,非常感谢
$(document).ready(function(){
$("#usersTable tr").click(function(){
$(this).find("td").each(function(index){
if (index === 0) {
console.log($(this).html());
}
});
});
})