Search code examples
javascript

Ancor is not added correctly


Ancor is added after # to the main page (site.com/#ancor) - the site domain. But it needs to be added to the current page (site.com/category/article#ancor)

Apparently there is an error here

 generateNavEl: function(anchor, text) {
        var $a = $('<a class="nav-link"></a>');
        $a.attr("href", "#" + anchor);
        $a.text(text);
        var $li = $("<li></li>");
        $li.append($a);
        return $li;
      },

Код взят отсюда


Solution

  • All the properties the Location interface exposes, can be accessed directly on a link as well - when you go via the DOM, instead of jQuery.

    $a[0].hash = "#" + anchor;
    

    $a[0] gets the reference to the native DOM element wrapped in this jQuery instance.

    And then only the hash portion of the location the link points to gets changed, leaving everything else, including the path, as it was.