Javascript 如何从定义的函数中选择单击的链接?
我正在构建一个AJAX导航站点(代码取自),该站点在标记中使用常规链接,但通过.js将它们替换为哈希链接 我不希望用户能够点击一个只会重新加载相同内容的链接。因为我使用散列,对于主页以外的任何页面(第一次加载时),这个问题会自行解决(如果用户单击当前URL散列的散列链接,则不会发生任何事情) 在我将其定义为函数之前,我有一个解决方案一直在工作(因为我需要重用它)。它使用$(this)获取已单击的链接,如果指向当前页面,则返回false。但是,现在它返回窗口(作为数组对象),而不是单击的链接 如何选择已单击的链接Javascript 如何从定义的函数中选择单击的链接?,javascript,jquery,ajax,hash,navigation,Javascript,Jquery,Ajax,Hash,Navigation,我正在构建一个AJAX导航站点(代码取自),该站点在标记中使用常规链接,但通过.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将匹配的元素设置为eventhandler中的上下文,因此
此
是委托事件处理程序中的HtmlanchereElement。但是在函数initiateHashNav
外部没有设置上下文,因此它只是窗口对象只需将$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将匹配的元素设置为eventhandler中的上下文,因此此
是委托事件处理程序中的HtmlanchereElement。但是函数initiateHashNav
的外部没有设置上下文,因此它只是窗口对象