I am trying to get the text in the first td
in the parent tr
which the clicked span
element is located.
I thought the following would work, but it returns text in all td
elements of the given tr
. How do I do this without doing something like $t.closest('tr').find('td').eq(0).text()
?
http://jsfiddle.net/9dh7pz73/3/
$("table span").click(function(){
var $t=$(this);
console.log($t.closest('tr'),$t.closest('tr').first('td').text());
});
<table>
<tr>
<td>a</td>
<td>0</td>
<td><span>xxx</span></td>
</tr>
<tr>
<td>b</td>
<td>0</td>
<td><span>xxx</span></td>
</tr>
<tr>
<td>c</td>
<td>0</td>
<td><span>xxx</span></td>
</tr>
</table>
The first()
method doesn't take a selector. Instead you could do find('td:first')
, like this:
$("table span").click(function(){ var $t = $(this); console.log($t.closest('tr').find('td:first').text()); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td>a</td> <td>0</td> <td><span>xxx</span></td> </tr> <tr> <td>b</td> <td>0</td> <td><span>xxx</span></td> </tr> <tr> <td>c</td> <td>0</td> <td><span>xxx</span></td> </tr> </table>
If you want to target the first <td>
element when a specific span is clicked, you could just wire up an event handler to pick up the click and then find the first <td>
via the td:first
selector:
$('table span').click(function(){
// This will find the closest <tr> and then the first <td> element that appears within
console.log($(this).closest('tr').find('td:first').text());
});
Example
$('table span').click(function() { console.log($(this).closest('tr').find('td:first').text()); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td>a</td> <td>0</td> <td><span>xxx</span> </td> </tr> <tr> <td>b</td> <td>0</td> <td><span>xxx</span> </td> </tr> <tr> <td>c</td> <td>0</td> <td><span>xxx</span> </td> </tr> </table>
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.