我有一个关于 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>
在这种情况下,点击事件不会触发警报。
有人可以解释一下我在这里遗漏了什么,或者这是否应该是这样工作的?
最佳答案
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/