我有以下代码:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Page</title>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".Note").click(function(){
$(this).parent().parent().next(".divNote").slideToggle();
});
});
</script>
</head>
<body>
<table>
<tr>
<td class="Note" style="cursor: pointer">
<font size="3" color="#800080"><b><u>TD</u></b> </font>
</td>
</tr>
</table>
<br />
<div style="display: none" class="divNote">
</div>
</body>
</html>
我可以弄清楚为什么它不起作用。
示例:Here
任何帮助。
最佳答案
让我解释一下为什么它不起作用
您已向 next()
函数添加了一个过滤器,该过滤器仅过滤掉匹配的元素。在您的情况下,它只包含一个没有匹配类名的元素 (br
),因此结果集被截断为零个元素。
让它发挥作用的方法
因此,您必须从所有兄弟元素中过滤掉下一个
元素,而不是简单地过滤下一个
元素:
$(document).ready(function() {
$(".Note").click(function(){
$(this).parents("table").siblings(".divNote").slideToggle();
});
});
或从所有下一个 sibling 中过滤掉(当 previous sibling 姐妹根本不相关时)
$(document).ready(function() {
$(".Note").click(function(){
$(this).parents("table").nextAll(".divNote").slideToggle();
});
});
关于使用parent()和next()选择器的jquery问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4258977/