Make anchor links refer to the current page when using <base>

后端 未结 12 1127
情书的邮戳
情书的邮戳 2020-11-30 03:29

When I use the html tag to define a base URL for all relative links on a page, anchor links also refer directly to the base URL. Is there a way to

相关标签:
12条回答
  • 2020-11-30 04:14

    You can use some javascript code inside the tag that links.

    <span onclick="javascript:var mytarget=((document.location.href.indexOf('#')==-1)? document.location.href + '#destination_anchor' : document.location.href);document.location.href=mytarget;return false;" style="display:inline-block;border:1px solid;border-radius:0.3rem"
     >Text of link</span>
    

    How does it work when the user clicks?

    1. First it checks if the anchor (#) is already present in the URL. The condition is tested before the "?" sign. This is to avoid the anchor being added twice in the URL if the user clicks again the same link, since the redirection then wouldn't work.
    2. If there is sharp sign (#) in the existing URL, the anchor is appended to it and the result is saved in the mytarget variable. Else, keep the page URL unchanged.
    3. Lastly, go to the (modified or unchanged) URL stored by the mytarget variable.

    Instead of <span>, you can also use <div> or even <a> tags. I would suggest avoiding <a> in order to avoid any unwanted redirection if javascript is disabled or not working, and emultate the look of your <a> tag with some CSS styling. If despite this you want to use the <a> tag, don't forget adding return false; at the end of the javascript and set the href attribute like this <a onclick="here the javascript;return false;" href="javascript:return false;">...</a>.

    0 讨论(0)
  • 2020-11-30 04:15

    Building upon @James Tomasino answer, this one is slightly more efficient, solves a bug with double hashes in the url and a syntax error.

    $(document).ready(function() {
        var pathname = window.location.href.split('#')[0];
        $('a[href^="#"]').each(function() {
            var $this = $(this),
                link = $this.attr('href');
            $this.attr('href', pathname + link);
        });
    });
    
    0 讨论(0)
  • 2020-11-30 04:15

    If you're using Angular 2+ (and just targeting the web) you can do this:

    component.ts

    document = document; // Make document available in template
    

    component.html

    <a [href]="document.location.pathname + '#' + anchorName">Click Here</a>
    
    0 讨论(0)
  • 2020-11-30 04:20

    i found a solution on this site: using-base-href-with-anchors that doesn't require jQuery and here is a working snippet:

    <base href="https://example.com/">
    
    <a href="/test">/test</a>
    <a href="javascript:;" onclick="document.location.hash='test';">Anchor</a>

    or without inline js, something like this:

    document.addEventListener('DOMContentLoaded', function(){
      var es = document.getElementsByTagName('a')
      for(var i=0; i<es.length; i++){
        es[i].addEventListener('click', function(e) {
          e.preventDefault()
          document.location.hash = e.target.getAttribute('href')
        })
      }
    })
    
    0 讨论(0)
  • 2020-11-30 04:24

    I'm afraid there is no way to solve this without any server-side or browser-side script. You can try the following plain JavaScript (without jQuery) implementation:

    document.addEventListener("click", function(event) {
      var element = event.target;
      if (element.tagName.toLowerCase() == "a" && 
          element.getAttribute("href").indexOf("#") === 0) {
        element.href = location.href + element.getAttribute("href");
      }
    });
    <base href="https://example.com/">
    
    <a href="/test">/test</a>
    <a href="#test">#test</a>

    It also works (unlike the other answers) for dynamically generated (i.e. created with JavaScript) a elements.

    0 讨论(0)
  • 2020-11-30 04:25

    My approach is to search for all links to an anchor, and prefix them with the document URL.

    This only requires javascript on the initial page load and preserves browser features like opening links in a new tab. It also and doesn't depend on jQuery/etc.

    document.addEventListener('DOMContentLoaded', function() {
      // get the current URL, removing any fragment
      var documentUrl = document.location.href.replace(/#.*$/, '')
    
      // iterate through all links
      var linkEls = document.getElementsByTagName('A')
      for (var linkIndex = 0; linkIndex < linkEls.length; linkIndex++) {
        var linkEl = linkEls[linkIndex]
      
        // ignore links that don't begin with #
        if (!linkEl.getAttribute('href').match(/^#/)) {
          continue;
        }
      
        // convert to an absolute url
        linkEl.setAttribute('href', documentUrl + linkEl.getAttribute('href'))
      }
    
    })
    
    0 讨论(0)
提交回复
热议问题