Select specific closest element
I have the following html :
<table id="objects">
<tr>
<td>
<input type="text" value="2" />
</td>
<td>
<a href="#" class="delete">link</a>
</td>
</tr>
<tr>
<td>
&l开发者_C百科t;input type="text" value="4" />
</td>
<td>
<a href="#" class="delete">link</a>
</td>
</tr>
</table>
When I click anchor tag I'd like to select <input>
closest to my link, and get it's value. How can I do this ? I was trying :
$('.delete').click(function(e){
e.preventDefault();
var val = $(this).closest('input').attr('value');
alert(val);
});
but without any luck.
If you look at the documentation for closest you will see that it says that it finds ancestors ..
Description: Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree.
the input in your case is not an ancestor of the .delete
link.
You need to move up with .closest('tr')
and then drill down to find the input with .find('input')
so
var val = $(this).closest('tr').find('input').val();
The name of the closest
function is extremely misleading: it's actually the closest ancestor that is returned.
The correct code would be:
var value = $(this).parent().siblings('td').children('input').val();
I wouldn't recommend binding the event handler to alllllllll anchor tags; this will be inefficient if there's a number of those elements on the page. Instead I would strongly recommend using delegate() or live() instead.
$('#objects').delegate('a.delete', 'click', function (e) {
e.preventDefault();
var val = $(this).parent('td').siblings('td').find('input').attr('value');
alert(val);
});
This will bind the event handler to the table
(once), and then uses JavaScripts event bubbling mechanisms to detect the click on the elements which match the selector passed in the first argument (in this case your delete buttons).
Try
$('.delete').click(function (e) {
e.preventDefault();
var val = $(this).parent("td").prev().find('input').val();
alert(val);
});
See Working Demo
You can't use closest
there, try this:
$('.delete').click(function(e){
e.preventDefault();
var val = $(this).parent('td').prev('td').find('input').attr('value');
alert(val);
});
The parent()
is used to go back to parent td
of the link and then prev()
is used to find the previous sibling of td
and finally with find
method, input
is searched for.
More Info:
- http://api.jquery.com/parent/
- http://api.jquery.com/prev/
- http://api.jquery.com/find/
精彩评论