[英]How can I get only one column value from html table?
I have a html table that shows a list of users ID, Name and E-mail. 我有一个html表,显示用户ID,名称和电子邮件的列表。 When my user clicks in any row, I get the id number of that row and send to my backend. 当用户单击任意行时,我将获得该行的ID号并发送到我的后端。 So, I did this: 因此,我这样做:
//Making the table
var trs = document.getElementsByTagName('tr');
for (var i = 0; i < trs.length; i++) {
trs[i].onclick = clickHandler;
}
Function that handles the click: 处理点击的函数:
function clickHandler(event) {
var numb = this.innerText.match(/\d/g);
numb = numb.join("");
window.location.replace("chooseParticipant.php?id="+numb);
}
Table Example: 表示例:
<div id="table">
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>E-mail</th>
</tr>
</thead>
<tbody>
<td>7</td>
<td>Test User</td>
<td>testuser123@example.com</td>
</tbody>
</table>
</div>
What happens then? 那会发生什么呢? If an user have numbers in their e-mail, the "numb" variable gets these numbers too. 如果用户的电子邮件中包含数字,则“ numb”变量也会获取这些数字。 I don't know how to filter only the id number. 我不知道如何仅过滤ID号。 Did someone have any ideas? 有人有什么想法吗?
You could assign a class to you tag. 您可以为标签分配一个类。 Something like below:- 如下所示:
<td class="id">7</td>
And in the javascript code you could fetch all the elements with class "id". 在javascript代码中,您可以获取所有带有“ id”类的元素。 And then perform your click handler on each one. 然后对每个按钮执行点击处理程序。
var trs = document.getElementsByClassName('id');
I hope this helps. 我希望这有帮助。
Try this code snippet which use data-*
attribute 试试这个使用data-*
属性的代码片段
document.addEventListener('DOMContentLoaded', function(e) { var trs = document.querySelectorAll('#table tbody tr'); var repeater = Array.prototype.slice; repeater.call(trs).forEach(function(tr) { tr.addEventListener('click', function(e) { var data = tr.querySelector('td[data-id]').dataset; console.log('id=', data.id); }); }); });
tbody { cursor: pointer; }
<div id="table"> <table border="1" cellspacing="0" cellpadding="3"> <thead> <tr> <th>ID</th> <th>Name</th> <th>E-mail</th> </tr> </thead> <tbody> <tr> <td data-id="7">7</td> <td>Test User 1</td> <td>testuser1231@gmail.com</td> </tr> <tr> <td data-id="8">8</td> <td>Test User 2</td> <td>testuser1232@gmail.com</td> </tr> <tr> <td data-id="9">9</td> <td>Test User 3</td> <td>testuser1233@gmail.com</td> </tr> </tbody> </table> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.