2010-02-09 68 views
1

有这样一个html:检测锚是导致积极window.location的

<a class="someclass" href="some/url/absolute/or/relative">Blah</a> 

...这样的JavaScript的一起:

$("a.someclass").onclick(function() { 
    var link = $(this).attr("href"); 
    if (link == window.location) // <<<<<<<<<<<< 
     doSomethingSpecial(); 
    else 
     doOtherThing(); 
    return false; 
}); 

这段代码显然是行不通的。

如何可靠地检测到某个锚点正在导致当前的浏览器位置?

这里有一些注意事项:

  • 锚的href可能是绝对或相对的。
  • 应该忽略URL的片段。

回答

1

的问题是,$('a').attr('href')始终返回相对路径。您需要使用本地obj.href属性得到的绝对路径,带哈希,然后比较:

var clean = function(str) { 
    return str.replace(/(\#.*)/,'').toLowerCase(); 
} 

$("a.someclass").click(function(e) { 
    if (clean(this.href) == clean(window.location)) { 
     // the link destination is equal to window.location (excluding hashes) 
     doSomethingSpecial(); 
    } else { 
     doOtherThing(); 
    } 
    e.preventDefault(); 
}); 

编辑:

如果你想比较路径名,你可以直接从锚抓住它元素:

$("a.someclass").click(function(e) { 
    if (this.pathname == window.location.pathnname) { 
     doSomethingSpecial(); 
    } else { 
     doOtherThing(); 
    } 
    e.preventDefault(); 
}); 
+0

@David:你确定'$('a')。attr('href')'总是返回相对路径吗?这将是非常好的,因为我可以比较'location.pathname'。但是,片段呢?... – 2010-02-09 10:56:25

+0

@Anton:看我的编辑。 – David 2010-02-09 12:22:24

+0

一些较旧的浏览器不在anchor.pathname中包含最初的'/',但它们在window.location.pathname上执行。如果你关心较旧的浏览器,那么在进行比较之前你需要检查它。 – Nicholas 2013-12-14 04:30:16

1

AFAIK,你无法检测到。因为我可以编写onclick事件处理程序,然后编写导致当前位置本身的代码。在这种情况下,你不能真正依赖于href属性。

function ReloadWin() 
{ 
    window.location.reload(); 
} 

<a href="#" onclick="ReloadWin();">Click me to reload</a> 
+0

你完全正确的'onclick',但是我需要检测锚点的'href'是否会导致当前位置。 – 2010-02-09 10:36:57

+0

这也会很困难,因为我也可以在'href'上写同样的事件。 – rahul 2010-02-09 10:41:18

+0

对我无所谓。我知道我的锚是用纯粹的href生成的。 – 2010-02-09 10:58:03

0

试试这个:

$(document).ready(function(){ 
    $("a.someclass").click(function(){ 

     //convert both to lower case 
     var h=$(this).attr("href").toLowerCase(); 
     var l=window.location.href.toLowerCase(); 

     //if has hash tag remove portion after if 
     if(l.indexOf("?")>0) 
      l=l.substring(0,l.indexOf("?")); 
     if(l.indexOf("#")>0) 
      l=l.substring(0,l.indexOf("#")); 

     if(l.length > h.length) 
      l = l.substring(l.length - h.length); 

     if(l==h){ 
      alert("On same page"); 
     }else{ 
      alert("Other page"); 
     } 
     return false; 
    }); 
});