-1

我正在学习 jQuery,正如您从我最后的问题中看到的那样。现在我尝试让一个非常大的静态 html 更易于导航。

html的一部分:

<a class="entryheader">...</a><br /><br />
<div class="entrycontent">...<br />
<p class="entryfoot">...</p>

<a class="entryheader">...</a><br /><br />
<div class="entrycontent">...<br />
<p class="entryfoot">...</p>

我的 JS:

$("a.entryheader").click(function(){
 alert("clicked");
 $(this).next("div.entrycontent").show();
});

Entrycontent 默认是隐藏的,只有在用户点击 entryheader 时才可见。

如果我点击 entryheader 我会得到消息框,但 entrycontent 保持不可见。

我为 $(this).next 尝试了不同的方法,但都没有奏效。

可能我缺乏对DOM模型的理解。您推荐哪些工具和文档?

4

3 回答 3

4

问题是next()在 html 中查找下一个元素。在您的情况下,您使用一堆BR标签作为分隔符,所以next()将是BR

最好的解决方案是使用您拥有的代码并删除BR标签并使用 CSS 应用边距进行分隔。

如果你保留BR标签,你可以使用index()方法

$("a.entryheader").click(function(){
     var index=$("a.entryheader").index(this)
     $("div.entrycontent").eq(index).show();
});

DEMO 使用索引 http://jsfiddle.net/fUeZE/

于 2012-10-16T11:48:59.303 回答
2

The other way of achieving what you want with your code is using jQuery's nextAll() traversal method to match all of the next elements with a class of .entrycontent but then filtering to just the first found like so.

$("a.entryheader").click(function(){ 
    $(this).nextAll('div.entrycontent').first().show();
}); 

DEMO

More info on .first() and .nextAll()

于 2012-10-16T11:55:11.003 回答
0

$(this).next('div.entrycontent')在你的情况下不会选择任何东西,因为锚标签之后的下一个兄弟是<br />标签。我会删除<br />标签并向锚标签添加一些边距底部以创建相同的效果,然后.next上面的代码将起作用。

于 2012-10-16T11:50:24.383 回答