How to set an event on the parent element using jQuery
help me figure out how to set an event on the parent element (<tr>
)
I can't find the error in the condition
<script type="text/javascript">
$('table tbody tr').each(function(){
$(this).f开发者_StackOverflow中文版ind('a:first').click(function(){
if($(this).parents().get(1).tagName == 'TR') {
$(this).parents().get(1).find('tr').css('background', 'red'); //What's wrong?
}
});
</script>
<table>
<tbody>
<tr>
<td><a href="#">text</a></td>
<td>text</td>
</tr>
</tbody>
</table>
Unfortunately, the formatting, I don't see any more special tag
hey you are missing closing });
for each
statement. Here is the correct version of your code
$('table tbody tr').each(function(){
$(this).find('a:first').click(function(){
if($(this).parents().get(1).tagName == 'TR') {
$($(this).parents().get(1)).css("background-color", 'red'); //What's wrong?
}
});
});
Working Example
EDIT: you can shorten above code very easily like assigning a class to anchor tag.
<a class="bindclick" href="#"></a>
$(".bindclick").bind("click", function(){
var parent = $(this).parents("tr").get(0);
OR
var parent = $(this).closest("tr"); // http://api.jquery.com/closest/
$(parent).css("background-color","red");
});
$('table tbody tr').each(function(){
var $this = $(this);
$this.find('a:first').click(function(){
$this.css('background', 'red');
});
});
crazy demo
$("table tr a:first").click(function() {
$(this).closest("tr").css('background', 'red');
});
Not completely sure about this, but I think that when you call $(this) inside the second function for clicking the a tag, $(this) is the a tag itself, and not the $(this) which is in the outer function the tr element.
$('table tbody tr').each(function(){
var $this = $(this);
$this.find('a:first').click(function(){
$this.css('background', 'red');
});
});
Edit: This works:
$(function() {
$('tr a:first').click(function() {
$(this).parents('tr:first').css({background:'red'});
});
});
$('table tbody tr').each(function(){
$(this).find('a:first').click(function(){
$(this).css('background', 'red');
});
});
easy one.
精彩评论