URL fragments and the BASE tag

老子叫甜甜 提交于 2019-12-11 00:43:58

问题


I'm using the <base> tag in an application to simplify development.

I'm aware of the "feature" that occurs when an anchor is only a URL fragment, as in it routes to the <base> URL + fragment.

What can I do to circumvent that? I've never fudged with window.location or anything in Javascript, and rather than hack around for awhile at it, I assume someone knows of a quick-and-dirty, or an example.

Can this be circumvented? If so, please advise.

(I hate asking questions that suggest no attempt has been made, but I've been searching/reading to little avail)

(Also; using jQuery, so any examples that would take advantage of vanilla Javascript or jQuery are welcome)


jQuery solution I hacked together, not sure if its viable as a permanent solution though, thoughts?

$('a').each(function(index){
    if($(this).attr('href').indexOf('#') == 0){
        $(this).attr('href', (window.location.href).replace(/#.*$/, '')
            + $(this).attr('href'));
    }
});

回答1:


Ok, so, I think I understand the question now.

This has been tested in Google Chrome and Firefox.

Add this javascript at the end of the body:

base=document.getElementsByTagName("base"); 
base=base[0].href;

links=document.getElementsByTagName('a');

for(index in links){
    if(links[index].href.indexOf(base+"#")==0){
        links[index].href=document.location+links[index].href.slice(links[index].href.indexOf("#"));
    }
}



回答2:


Don't use relative urls. The base tag won't affect urls like /home or http://google.com, but it will effect about/us or users/12



来源:https://stackoverflow.com/questions/6779839/url-fragments-and-the-base-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!