如何从定义的函数中选择单击的链接

How can I select the clicked link from a defined function?

本文关键字:选择 单击 链接 函数 定义      更新时间:2023-09-26

我正在构建一个AJAX可导航站点(代码取自CSS-Tricks(,它在标记中使用常规链接,但通过.js将它们替换为哈希链接。

我不希望用户能够单击只会重新加载相同内容的链接。因为我使用的是哈希,所以对于主页以外的任何页面(首次加载时(,此问题会自行解决(如果用户单击当前 URL 哈希的哈希链接,则没有任何反应(。

有一个解决方案,直到我将其定义为函数(因为我需要重用它(。它使用 $(this( 来获取已单击的链接,如果指向当前页面,则返回 false。但是,现在这将返回窗口(作为数组对象(而不是单击的链接。

如何选择点击的链接?

// Use hashes instead of reloads to navigate the site.
function initiateHashNav(linkContainers) {
  var $this = $(this);
  $(linkContainers).delegate('a', 'click', function() {
    // Restrict clicking on link for current page.
    if ($this.attr('href') == window.location.href) {
      return false;
    } else {
      // The hash shouldn't contain window.location (clean URLs are happy URLs!).
      window.location.hash = $this.attr('href').substr(window.location.origin.length);
      return false;
    }
  });
}

只需将$this声明移动到正确的范围内,如下所示:

function initiateHashNav(linkContainers) {
  $(linkContainers).delegate('a', 'click', function() {
     var $this = $(this);
    // Restrict clicking on link for current page.
    if ($this.attr('href') == window.location.href) {
      return false;
    } else {
      // The hash shouldn't contain window.location (clean URLs are happy URLs!).
      window.location.hash = $this.attr('href').substr(window.location.origin.length);
      return false;
    }
  });
}

JavaScript中的每个函数都是一个作用域。中的每个作用域都有一个上下文 (this(,如果未设置上下文,则窗口对象将成为上下文。

jQuery.fn.delegate 将匹配的元素设置为事件处理程序中的上下文,因此this是委托事件处理程序中的 HtmlAncherElement。但是在函数initiateHashNav之外没有设置上下文,所以它只是窗口对象