[英]Get td parent and tr child
我需要从第一个TD单击按钮获取值“ TEST1”。 我尝试使用Javascript,但无法正常工作。打印结果使我不确定。
<table style="width:100%">
<tr>
<td>TEST1</td>
<td>TEST2</td>
<td><button class='x' type='button' onclick='openindex()' >value='button'</button></td>
</tr>
</table>
这是我的Javascript函数,由于找不到最接近的Tr,但我的子属性不起作用,所以我无法弄清楚自己在做什么
function openindex(){
var $row = $(this).closest("tr");
$tds = $row.find("td:nth-child(1)").value;
alert($tds);
}
您在没有显式上下文的情况下调用openindex()
,因此this
(在其内部)将是window
而不是元素。
您可以通过:
onclick="openindex.call(this)"
但您应该首先避免使用onclick
属性,而应使用jQuery().on
绑定函数。
jQuery('button').on('click', openindex);
我想你只需要使用
$tds = $row.find("td:nth-child(1)").text();
代替
$tds = $row.find("td:nth-child(1)").value;
您还应该使用var关键字设置变量,以使其不是全局变量,并且由于它仅返回字符串,因此不需要$。
var tds = $row.find("td:nth-child(1)").text();
或者完全是另一种方式
$('.x').click(function () {
var $row = $(this).closest("tr");
var tds = $row.find('td').first().text();
alert(tds);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.