jQuery add text before href attribute

微笑、不失礼 提交于 2019-12-13 08:56:17

问题


How can I add text to before a href attribute?

Example:

<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=]');

回答1:


You can use a callback function with attr:

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

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

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

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.




回答2:


Just change href attribute:

$('a:not([href*="//"])').attr(function(_, href){
    return "http://www.example.com" + href;
});


来源:https://stackoverflow.com/questions/16739832/jquery-add-text-before-href-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!