【问题标题】:How can I select the clicked link from a defined function?如何从定义的函数中选择单击的链接?
【发布时间】:2012-05-23 14:55:30
【问题描述】:

我正在构建一个 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;
    }
  });
}

【问题讨论】:

    标签: javascript jquery ajax hash navigation


    【解决方案1】:

    只需将$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之外没有设置上下文,所以它只是窗口对象

    【讨论】:

      猜你喜欢
      • 2012-08-07
      • 1970-01-01
      • 2021-07-27
      • 2011-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-17
      • 2020-03-28
      相关资源
      最近更新 更多