1

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

1 回答 1

1

Just move the declaration of $this into the correct scope like 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;
    }
  });
}

Every function in javascript is a scope. Each scope in has a context (this) and if one is not set, the window object becomes the context.

jQuery.fn.delegate sets the matched element as context in the eventhandler, thus this is a HtmlAncherElement inside the delegate event handler. But outside in the function initiateHashNav there is no set context,and so it is just the window object

于 2012-05-16T04:24:39.093 回答