使用javascript获取已单击项的父项
你好,我正在尝试根据td点击获取tr的id 这是我的按钮代码:使用javascript获取已单击项的父项,javascript,html,Javascript,Html,你好,我正在尝试根据td点击获取tr的id 这是我的按钮代码: while ($stmt->fetch()) { echo'<tr id="'.$id.'"> <td><button type="button" onclick="removeSet(this)"><img src="images/program/trash.png"></button></td>
while ($stmt->fetch())
{
echo'<tr id="'.$id.'">
<td><button type="button" onclick="removeSet(this)"><img src="images/program/trash.png"></button></td>
</tr>';
}
我的问题是我得到了这个错误:
未捕获的TypeError:无法读取未定义的属性“parentNode”
请改用此功能:
function removeSet(cell)
{
var id = cell.parentNode.parentNode.getAttribute('id');
alert(id);
}
问题是您的函数得到了按钮的父级(td),而不是td的父级(tr)
要获取tr的id,您需要按钮父项的父项。您忘记在tr中添加td。
这是您应该使用的html语法:
<table>
<tr id="customId">
<td>
<button type="button" onclick="removeSet(this)">
<img src="images/program/trash.png"/>
</button>
</td>
</tr>
</table>
你不应该犯这个错误。
<table>
<tr id="customId">
<td>
<button type="button" onclick="removeSet(this)">
<img src="images/program/trash.png"/>
</button>
</td>
</tr>
</table>
function removeSet(cell) {
var id = cell.parentNode.parentNode.getAttribute('id');
alert(id);
}