简体   繁体   English

使用jQuery在锚链接之前添加当前页面URL

[英]Add Current Page URL Before Anchor Link Using jQuery

I am stuck utilizing a platform (Nationbuilder) that automatically adds the base tag in the header. 我被困在利用一个平台(Nationbuilder)上,该平台会自动在标头中添加基本标签。 It didn't until recently and now the dozens of pages with anchor links end up sending the user to the homepage. 直到最近,几十个带有锚链接的页面最终将用户引导到主页。

I need to use jQuery to add the current page's url before the #anchor. 我需要使用jQuery在#anchor之前添加当前页面的url。 The closest I can find is the following code, but I have no idea how to modify it so ONLY links with a href attribute starting with a # are modified: 我能找到的最接近的是以下代码,但是我不知道如何修改它,因此仅修改以#开头的href属性的链接:

$("a").attr("href", "http://www.example.com/pageslug")

So I would like: 所以我想:

<a href="#anchorname"></a>

To be changed to: 更改为:

<a href="http://www.example.com/pageslug#anchorname"></a>

You can use the CSS attribute starts with selector: 您可以使用以选择器开头的CSS属性:

Instead of selecting "a" , select 'a[href^="#"]' meaning "a tags with an href attribute starting with # . 而不是选择"a" ,而是选择'a[href^="#"]'意思是“带有以#开头的href属性的标签。

So something like: 所以像这样:

$('a[href^="#"]').each(function(i,el){
    el.href = "http://www.example.com/pageslug" + el.hash;
});

(fiddle) (小提琴)

One addition to what Benjamin said, you'll need to capture the current href for each of the anchors, which means you need a loop. 除了本杰明所说的内容,您还需要捕获每个锚点的当前href,这意味着您需要一个循环。 So 所以

$('a[href^="#"]').each(function(index, element){
    var $ele = $(element),
        oldHref = $ele.attr('href');
    $ele.attr('href', '//example.com/page'+ oldHref);
});

像这样吗

$('a').attr('href', window.location.pathname + this.attr('href'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用锚链接将查询字符串添加到 url - Add query string to url using anchor link 添加查询字符串以锚定当前URL中嵌入的查询的链接 - Add a query string to anchor link from query embedded in current URL 链接到不同页面上的锚点和scroolTo使用JQuery锚点 - link to anchor on different page and scroolTo anchor using JQuery jQuery在页面加载之前更改当前页面URL的一部分 - jquery change part of the current page url before page load 如何在转到链接之前重新加载当前页面? ajax jquery - How to reload current page before going to link? ajax jquery 在img之前添加并关闭在jquery中使用的定位标记 - before img add and close anchor tag using in jquery 如何使用?parameter = only链接重新加载页面并替换Jquery Mobile中的当前锚页面? - how to reload a page with ?parameter=only link and replace the current anchor page in Jquery Mobile? 链接到另一页上带有一堆图像的锚点 - link to an anchor on another page with a bunch of images before it 获取用户访问过的上一页URL,并使用jQuery将类添加到当前页面上的元素 - Get previous page URL a user has visited and add class to element on current page using jQuery 将当前页面URL写入微数据的定位标记 - Write current page URL into anchor tag for microdata
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM