Get the value of children in jquery
How to get the value of cell in a table when the user click on the next cell?
<table id="registrarsTable">
<c:forEach items="${requestScope.AllUsers}" var="user" varStatus="loop">
<tr class="userRow">
<td class="numberWidth">${loop.index + 1}</td>
<td class="nameWidth user" id="${user.userno}">${user.fullName}</td>
<td>
<button name="DeactivateBtn" 开发者_Python百科 id="deactivate" class="deactivate btn">deactivate</button>
</td>
</tr>
</c:forEach>
in jquery I want to get the value of attribute "id" from second td
when user click on deactivate button.
I make like this
var userNo = $('td.user', $(this).parents(".userRow")).attr('id');
and like this
var userNo = $($(this).parent(".userRow") > "td").attr("id");
and no one works!
$('#deactivate').click(function() {
var userNo = $(this).parent().prevAll('td.user').attr('id');
});
From the button (which is this
), traverse up to the parent (the <td>
containing the deactivate button). Then, to the previous sibling <td>
with the class user
, and get the id
attribute.
Alternatively, if you want to avoid relying on the fact the the deactivate button is in a <td>
after the user name's <td>
, you can do this:
$('#deactivate').click(function() {
var userNo = $(this).closest('tr').find('td.user').attr('id');
});
Which finds the parent <tr>
with closest
and then the <td class="user">
with find
.
Working example: http://jsfiddle.net/FishBasketGordo/Bk6ML/
API References:
parent()
- http://api.jquery.com/parentprevAll()
- http://api.jquery.com/prevAllclosest()
- http://api.jquery.com/closestfind()
- http://api.jquery.com/find
精彩评论