简单表:
<table class="schedules">
<th colspan="2">Saved Schedules</th>
<tr>
<td>Winter 2011 </td>
</tr>
<tr>
<td>Winter 2011 (2) </td>
</tr>
<tr>
<td>May Term 2011 </td>
</tr>
<tr>
<td>Fall Term 2011</td>
</tr>
</table>
Jquery的:
<script type="text/javascript">
$(document).ready(function(){
$(".schedules td").click(function(){
$(this).css("background-color","blue")
$(this).siblings().css("background-color","white");
});
});
</script>
这应该将选定的单元格切换为背景颜色:蓝色,将兄弟姐妹切换为背景颜色:白色,但是当我单击每个单元格时,只需更改为背景颜色:蓝色,其他单元格根本不会更改。 / p>
答案 0 :(得分:5)
你的<td>
是表兄弟,而不是兄弟姐妹。 td的父母(<tr>
)是兄弟姐妹。你可以像这样修改jquery ......
http://jsfiddle.net/superuntitled/fb4g7/
$(document).ready(function(){
$(".schedules tr").click(function(){
$(this).find('td').css("background-color","blue")
$(this).siblings().find('td').css("background-color","white");
});
});
答案 1 :(得分:2)
其他<td>
元素不是兄弟姐妹。
您可以使用closest()
[docs]方法遍历共同祖先,然后使用find()
[docs] <td>
元素遍历。
$(document).ready(function(){
$(".schedules td").click(function(){
$(this).css("background-color","blue")
.closest('table').find('td').not(this).css("background-color","white");
});
});
或者您可以遍历<tr>
,然后使用.siblings()
,然后使用children()
[docs]方法。
$(document).ready(function(){
$(".schedules td").click(function(){
$(this).css("background-color","blue")
.parent().siblings().children('td').css("background-color","white");
});
});
修改强>
或者最有效的方法是缓存您的<td>
元素,并排除当前。
$(document).ready(function(){
var tds = $(".schedules td").click(function(){
$(this).css("background-color","blue");
tds.not(this).css("background-color","white");
});
});
完全消除处理程序内的DOM选择。
通常,您应该尝试缓存选择而不是重复它们。