在 jQuery 中从书签标签 (#bookmark) 遍历?

发布于 2024-08-29 12:17:18 字数 834 浏览 4 评论 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 (

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

谢谢!

I am having trouble traversing from a bookmark has tag in jquery. Specifically, the following 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>

I am trying to traverse to where the class = "title", if the page is landed on with a bookmark hashtag in the URL (site.com/test.html#comment-1). The following is my code I'm using for testing:

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

It executes fine, and returns the appropriate html (<h2 class="title"><a href="#co...)

The problem is if I add a selector to it ($(window.location.hash).next('.title').html() ) I get a null result. Why is this so? Is nextAll not the correct Traversing function? (I've also tried next+find to no avail)

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小梨窩很甜 2024-09-05 12:17:18

The $('#comment-1') selector selects the <a> element. The next method looks at the next sibling node of that element. There is no such node with a class of "title", so you get an empty result. In your example, the only sibling node of <a> is the div with class="comment". To find the <h2 class="title"> element, you can use e.g.:

$(window.location.hash).next().children('.title')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文