[英]How to get innerHTML of td in dynamically populated table in JavaScript
[英]How get the second td innerHTML
场景:
我正在使用数据表库来显示很多信息。 该表具有以下行:
Id Type Name Case
我要寻找的是,当我单击第二行Type时 ,该值将被获取并粘贴到文本框中
例
Id Type Name Case
1 text Juan 20001
3 List Pedro 20005
如果单击ID为1的行,则需要输入类型innerHTML。 没关系,我单击行的第二行只是获取第二个td的html。
我尝试使用以下代码:
$("tr td").click(function () {
alert($(this).html());
})
效果很好,但是问题是用户必须精确地单击行名,但是如果用户可以单击任何行并仅将第二行作为html,那会更好。
Suggesstions?
尝试使用eq()
但如果用户可以单击任意行并仅将第二行作为html,那会更好。
$("tr td").click(function () {
secondrow = $(this).closest('tr').siblings().eq(1);
});
如果我单击ID为1的行,则需要输入类型innerHTML。 没关系,我单击行的第二行只是获取第二个td的html。
$("tr td").click(function () {
secondTd = $(this).siblings().eq(1);
alert(secondTd.html());
});
myRow.getElementsByClassName('td')[1].innerHTML
只要第一个表单元格不包含嵌套表,就应该为您获取myRow
的第二个表单元格的innerHTML
。
您可以尝试将点击处理程序添加到行中,而不是添加到单元格中。
尝试这个
$(function () {
$("#thetable tr").click(function () {
if ($(this).index() == 0) return;
$('#tbox').val($('td:nth-child(2)', $(this)).html())
})
});
<table border="1" cellpadding="4" id="thetable">
<tr>
<td>Id</td>
<td>Type</td>
<td>Three</td>
<td>Four</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
</tr>
</table><br />
<input type="text" name="tbox" id="tbox" />
It方法考虑了仅包含标签的第一行,并且如果单击第一行,则不会将文本框的值设置为标签。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.