问题
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