使用jQuery在锚定链接之前添加当前页面URL [英] Add Current Page URL Before Anchor Link Using jQuery

查看:97
本文介绍了使用jQuery在锚定链接之前添加当前页面URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被困在利用一个平台(Nationbuilder)上,该平台会自动在标头中添加基本标签.直到最近,几十个带有锚链接的页面最终将用户引导到首页.

I am stuck utilizing a platform (Nationbuilder) that automatically adds the base tag in the header. It didn't until recently and now the dozens of pages with anchor links end up sending the user to the homepage.

我需要使用jQuery在#anchor之前添加当前页面的url.我能找到的最接近的是以下代码,但是我不知道如何修改它,因此只能修改带有以#开头的href属性的链接:

I need to use jQuery to add the current page's url before the #anchor. 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:

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

所以我想:

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

要更改为:

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

推荐答案

您可以使用以选择器开头的CSS属性:

You can use the CSS attribute starts with selector:

选择'a[href^="#"]'而不是选择"a",意思是带有以#开头的href属性的标签.

Instead of selecting "a", select 'a[href^="#"]' meaning "a tags with an href attribute starting with #.

所以像这样:

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

(小提琴)

这篇关于使用jQuery在锚定链接之前添加当前页面URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆