4

I have an ajax call attached to the click event of a pic inside a table row. Once the pic is clicked and the click event initiated, I need to grab the first and second td elements from that row. I'm new to jQuery so what I have below is my latest attempt (not working..). The variables firstName and lastName both wind up being undefined after those lines are executed

        $('.checkErrors').click(function () {
            var firstName = $(this).parent('tr td:first-child').val();
            var lastName = $(this).parent('tr td:nth-child(2)').val();
            $.ajax({
                type: 'GET',
                url: '@Url.Action("GetErrors","AgentTransmission")',
                data: { term: $(this).attr('id') },
                .
                .
            });
          });

Here is a sample table row. The image in the last td element contains the .click event. I would like to grab the first two that contain the text "phinneas" and "ferbseven".

<tr>
    <td>
        phinneas
    </td>
    <td>
        ferbseven
    </td>
    <td nowrap>
        7735        
    </td>
    <td>
        Agent
    </td>
    <td>
        SAF
        &nbsp;&nbsp
        07070900  
    </td>
    <td>
        6/5/2013 10:35:38 AM
    </td>
    <td>
        DANTAK
    </td>
    <td class="errorPlus">
        Error
    </td>            
    <td>

        <a href="/AgentTransmission/Details/2358">Details</a>           
            <span> | </span>
        <a href="/AgentTransmission/Edit/2358">Edit</a>        
    </td>
    <td align=center id=2358>
            <img src="/Content/images/magnify.gif" class="checkErrors" id=2358 alt="Program Details" />
    </td>
</tr>
4

3 回答 3

6

利用closest

var $tr = $(this).closest(´tr´);
var firstName = $tr.find('td:first-child').text();
var lastName = $tr.find('td:nth-child(2)').text();

此外,您需要使用text而不是valfortd元素,因为它仅对输入控件有意义。

于 2013-06-07T17:38:04.497 回答
2

First only form elements have .val property so .

You are supposed to use .text since it is a td

Try using :eq psuedo selector

var $tr;
$tr.find('td:eq(0)').text();

$tr.find('td:eq(1)').text();
于 2013-06-07T17:36:31.653 回答
1

要获取他们的内容,您可以这样做:

var cells = $(this).closest('td').siblings('td');
var firstName = cells.eq(0).text();
var firstName = cells.eq(1).text();

最后两行也可以是:

var firstName = $(cells[0]).text();
var firstName = $(cells[1]).text();
于 2013-06-07T17:37:58.250 回答