开发者

Detect anchor is leading to an active window.location

Having such an html:

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

... along with such javascript:

$("a.someclass").onclick(function() {
    var link = $(thi开发者_运维百科s).attr("href");
    if (link == window.location) // <<<<<<<<<<<<
        doSomethingSpecial();
    else
        doOtherThing();
    return false;
});

this code obviously doesn't work.

How to reliably detect that some anchor is leading to the current browser location?

Here are some notes:

  • Anchor's href could be either absolute or relative.
  • the fragments of the URLs should be ignored.


The problem is that $('a').attr('href') always returns the relative path. You need to use the native obj.href attribute to get the absolute path, strip hashes and then compare:

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();
});

EDIT:

If you want to compare pathnames, you can grab it directly from the anchor element:

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


AFAIK, you cannot detect that. Because I can write onclick event handler and then write the code that leads to the current location itself. In this case you can't really depend n the href attribute.

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

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


try this:

$(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;
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜