gpt4 book ai didi

javascript - 页面 anchor 链接的 jQuery this.hash 行为

转载 作者:技术小花猫 更新时间:2023-10-29 12:30:16 27 4
gpt4 key购买 nike

我有一个关于 this.hash 如何在 jQuery 中用于页面内 anchor 链接的问题。

每次用户单击该链接时,我都需要处理哈希属性。

<a href="#foo" class="inpageLink">Click Me!<"/a>
...
...
<a id="foo"></a>
<h3>Target Location</h3>

对于上面的 HTML 片段,当我获取哈希属性时,一切正常。

$('.inpageLink').click(function(){
var target = $(this.hash);
if (target.length != 0) {
alert("found target" + this.hash);
}
})

但是,当我为目标使用名称属性而不是 id 属性时,this.hash 返回一个空对象。

<a href="#bar" class="inpageLink">Click Me!</a>
<a name="bar"></a>
<h3>Target Location</h3>

在这种情况下,点击事件不会触发警报。

The full example is here

有人可以解释一下我在这里遗漏了什么,或者这是否应该是这样工作的?

最佳答案

this.hash将返回 "#foo"这也是一个有效的 ID selector [docs] .因此 $(this.hash)$("#foo")相同并将选择具有 ID foo 的元素.
在第二个示例中,您没有 ID 为 bar 的元素.因此 $(this.hash)不会选择任何元素和 target.length将是 0 .


也许你对浏览器仍然跳转到<a name="bar"></a>感到困惑, 虽然 alert未显示。浏览器的行为与 jQuery 不同。

来自HTML specification about the name attribute :

This attribute names the current anchor so that it may be the destination of another link. The value of this attribute must be a unique anchor name. The scope of this name is the current document. Note that this attribute shares the same name space as the id attribute.

因此,如果浏览器识别出 URL 中的散列(片段标识符),它会尝试查找具有此 ID 的第一个元素或第一个 a具有该名称的元素。

相比之下,CSS ID 选择器(这就是 jQuery 使用的)只搜索具有该 ID 的元素,而不搜索具有该名称的 ( a) 元素。在内部,jQuery 使用 document.getElemenById .


如果散列值总是引用 ID 或名称,您可以使用多重选择器 只进行一个选择:

$(this.hash + ', a[name="' + this.hash.substr(1) + '"]')

如果存在具有此 ID 的元素具有此名称的 anchor ,您可以选择所有这些元素。

关于javascript - 页面 anchor 链接的 jQuery this.hash 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9656949/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com