jQuery:如何在hashchange事件处理程序中查找元素

jQuery: How to find an element inside of hashchange event handler?

本文关键字:程序 查找 元素 事件处理 hashchange jQuery      更新时间:2023-09-26

一个网页有一些链接:

<a href="#example-hash-1" class="link">example-1</a>
<a href="#example-hash-2" class="link">example-2</a>
<a href="#example-hash-n" class="link">example-n</a>

点击它们中的任何一个,它将运行一个hashchange事件,我们将处理它:

$(window).on('hashchange', function(event){
    // Is it possible (inside this handler) to find out which of a.link was clicked?
});

或者,还有其他方法吗?

虽然我认为在实际链接中添加单击侦听器是最好的,但您也可以搜索会更改散列的元素,如下所示:

$(window).on('hashchange', function(event){
    $('a[href$='+window.location.hash+']').action();
});

我认为您可以使用onclick作为标签中的属性,或者您可以通过jQuery使用.click()事件。我认为这将完成与hashchange窗口相同的功能。

event.target将保存触发事件的元素。

我现在不能检查,但我相信this也绑定。

try this:

$(window).on('hashchange', function(event){
    var hash = location.hash;
    var $this = $(hash);
    alert($this.html());
});