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

标签 javascript jquery html

我有一个关于 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/

相关文章:

javascript - JQuery 淡入淡出悬停效果 - 帮助?

javascript - 使用 jQuery 动态自动递增 HTML 表格行值

javascript - 如何从 html 事件传递(或引用) "$(this)"?

javascript - AngularJS 在表中嵌套 ng-repeat

javascript - 为什么在 React JS jsx 中使用 map 时会出现未捕获的类型错误?

jquery - Angular 指令和 Jquery slipToggle 函数实现

javascript - Jest 错误 '' 类型错误 : Cannot read property 'preventDefault' of undefined "

jQuery 传递 CSS 变量

javascript - Jquery 错误消息显示在每个字段上

html - 为什么形成丢失的 Bootstrap css?