帮我弄清楚如何在父元素上设置事件(<tr>
)
我在条件
<script type="text/javascript">
$('table tbody tr').each(function(){
$(this).find('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>
不幸的是,格式化,我没有看到更多特殊标签
答案 0 :(得分:1)
$('table tbody tr').each(function(){
var $this = $(this);
$this.find('a:first').click(function(){
$this.css('background', 'red');
});
});
答案 1 :(得分:1)
$("table tr a:first").click(function() {
$(this).closest("tr").css('background', 'red');
});
答案 2 :(得分:1)
嘿,你错过了关于});
的each
声明。这是您的代码的正确版本
$('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 强> 的
编辑:您可以非常轻松地缩短上述代码,例如将类分配给锚标记。
<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");
});
答案 3 :(得分:0)
编辑:这有效:
$(function() {
$('tr a:first').click(function() {
$(this).parents('tr:first').css({background:'red'});
});
});
答案 4 :(得分:0)
不完全确定这一点,但我认为当你在第二个函数中调用$(this)来点击a标签时,$(this)是一个标签本身,而不是$(this)所在的外部函数是tr元素。
答案 5 :(得分:0)
$('table tbody tr').each(function(){
var $this = $(this);
$this.find('a:first').click(function(){
$this.css('background', 'red');
});
});
答案 6 :(得分:0)
$('table tbody tr').each(function(){
$(this).find('a:first').click(function(){
$(this).css('background', 'red');
});
});
很容易。