简体   繁体   中英

Get td parent and tr child

I need to get the value "TEST1" from the first TD clicking on the button. I tried the Javascript but it doesn't work.. The print gave me undefined.

   <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

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.

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.

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 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);
 })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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