jQuery在href属性之前添加文本 [英] jQuery add text before href attribute

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

问题描述

如何在href属性之前添加文本?​​

How can I add text to before a href attribute?

示例:

<a href="/page/subpage">Link!</a>

To:

<a href="http://www.example.com/page/subpage">Link!</a>

我试过这个,这是不工作:

I have tried this, which is not working:

$('http://www.example.com').insertBefore('a[href=]');


推荐答案

您可以使用回调函数 attr

$('a[href]').attr('href', function(index, href) {
    if (href.indexOf('http') === 0) {
        return href;
    } else {
        return 'http://www.example.com' + href;
    }
});

更隐蔽的方法是使用 < base> 标签

The more cryptic way would be to use the <base> tag:

$('<base href="http://www.example.com/">').appendTo('body');

或者只是将它放入您的HTML:

Or just put it into your HTML:

<base href="http://www.example.com/">

会强制所有相对网址相对于此网址解析。

It'll force all relative URLs to resolve relative to this URL.

这篇关于jQuery在href属性之前添加文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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