【问题标题】:Traversing from Bookmark Hashtags (#bookmark) in jQuery?从 jQuery 中的书签标签 (#bookmark) 遍历?
【发布时间】:2010-09-01 06:14:00
【问题描述】:

我在浏览带有 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 (&lt;h2 class="title"&gt;&lt;a href="#co...)

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

谢谢!

【问题讨论】:

  • 嗯,有什么问题?
  • 问题是如果我向它添加一个选择器 ($(window.location.hash).next('.title').html() ) 我得到一个空结果,而不是实际选择

    - 如果 URL 中有书签哈希标签,我要做的是显示/隐藏一些页面内容 - 即,如果 URL 中存在评论 1,则仅显示它

标签: jquery jquery-selectors traversal jquery-traversing


【解决方案1】:

【讨论】:

    【解决方案2】:

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

    $(window.location.hash).next().children('.title')
    

    【讨论】:

    • 感谢您的洞察力 - 因此我使用 find() 来解决此问题:$(window.location.hash).next().find('.title')
    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 2010-09-08
    • 1970-01-01
    • 2015-01-11
    • 2016-10-14
    • 1970-01-01
    • 2013-07-14
    • 1970-01-01
    相关资源
    最近更新 更多