简体   繁体   English

获取TD父母和TR孩子

[英]Get td parent and tr child

I need to get the value "TEST1" from the first TD clicking on the button. 我需要从第一个TD单击按钮获取值“ TEST1”。 I tried the Javascript but it doesn't work.. The print gave me undefined. 我尝试使用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>

Here is my Javascript function, I can't figure out what I'm doing wrong because I find the closest Tr but the child property doesn't work 这是我的Javascript函数,由于找不到最接近的Tr,但我的子属性不起作用,所以我无法弄清楚自己在做什么

function openindex(){
    var $row = $(this).closest("tr");
        $tds = $row.find("td:nth-child(1)").value;
 alert($tds);
}

You are calling openindex() without an explicitly context, so this (inside it) will be window and not the element. 您在没有显式上下文的情况下调用openindex() ,因此this (在其内部)将是window而不是元素。

You could pass it: 您可以通过:

onclick="openindex.call(this)"

but you should avoid using onclick attributes in the first place and bind your functions with jQuery().on instead. 但您应该首先避免使用onclick属性,而应使用jQuery().on绑定函数。

jQuery('button').on('click', openindex);

I think you just need to use 我想你只需要使用

$tds = $row.find("td:nth-child(1)").text();

instead of 代替

$tds = $row.find("td:nth-child(1)").value;

You should also use the var keyword to set the variable so it is not a global variable and since it is just returning a string there is no need for the $ so 您还应该使用var关键字设置变量,以使其不是全局变量,并且由于它仅返回字符串,因此不需要$。

 var tds = $row.find("td:nth-child(1)").text();

Or another way altogether would be 或者完全是另一种方式

$('.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM