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

后端 未结 12 1183
情书的邮戳
情书的邮戳 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: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");
      }
    });
    
    
    /test
    #test

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

提交回复
热议问题