JQUERY选择第一个<a> in the first of a

时间:2017-01-02 21:29:18

标签: javascript jquery html

I have the following markup:

<tr>
    <td>
        <a>foo</a></td>
    <td>bar</td>
    <td>
       <a class="delete-btn">delete</a>
    </td> 
</tr>

Now, I've already hooked up a on click event using jquery $(".delete-btn") the problem is that the click event handler need the text in the first element (foo).

I'm already getthin it with this call:

$(this).closest("tr").children().first().children().first("a")

but seriously... it looks wrong :-/ Maybe there is a better way to accomplish this?

2 个答案:

答案 0 :(得分:3)

我也不喜欢这个,但是......这正是你要找的东西:

$(this).closest("tr").find("> td:first-child > a");

答案 1 :(得分:2)

您可以使用jQuery&#39; :first伪选择器。

在这种情况下,您的整个选择器将是:

  • $('tr td:first a:first')(仅针对第一个<tr>
  • $('tr').find('td:first a:first')(适用于每<tr>

示例:

&#13;
&#13;
$(document).ready(function(){

    $('.delete-btn').click(function(){
        $('tr').find('td:first a:first').hide();
    })

});
&#13;
table, tr, td {
border: 1px solid rgb(191,191,191);
border-collapse: collapse;
}

td {
padding: 12px;
}

.delete-btn {
cursor: pointer;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
<tr>
<td><a>foo</a></td>
<td>bar</td>
<td><a class="delete-btn">delete</a></td> 
</tr>
<tr>
<td><a>foo</a></td>
<td>bar</td>
<td><a>baz</a></td> 
</tr>
</table>
&#13;
&#13;
&#13;