0

我无法从 jquery 中带有标签的书签进行遍历。具体来说,以下 HTML:

<a id="comment-1"></a> 
<div class="comment"> 
<h2 class="title"><a href="#comment-1">1st Post</a></h2> 
  <div class="content">
    <p>this is 1st reply to the original post</p> 
  </div> 
  <div class="test">1st post second line</div>
  </div>

如果页面在 URL (site.com/test.html#comment-1) 中带有书签主题标签,我正在尝试遍历到 class = "title" 的位置。以下是我用于测试的代码:

if(window.location.hash) {
alert ($(window.location.hash).nextAll().html());
}

它执行得很好,并返回适当的 html ( <h2 class="title"><a href="#co...)

问题是如果我向它添加一个选择器 ( $(window.location.hash).next('.title').html()),我会得到一个空结果。为什么会这样?nextAll 不是正确的遍历函数吗?(我也试过next+find无济于事)

谢谢!

4

2 回答 2

3

有一个 jquery 插件:http: //github.com/shanbady/Jquery-ajaxBookmarkable

于 2010-08-31T22:14:00.600 回答
2

选择器$('#comment-1')选择<a>元素。该next方法查看该元素的下一个兄弟节点。没有具有“标题”类的此类节点,因此您得到一个空结果。在您的示例中,唯一的兄弟节点<a>是具有 class="comment" 的 div。要查找<h2 class="title">元素,您可以使用例如:

$(window.location.hash).next().children('.title')
于 2010-04-19T01:33:34.773 回答