将jquery或javascript中的内部链接更改为外部链接

3

我正在开发一个应用程序,该应用程序从不同的网站获取其内容。在获得的内容中有时会出现内部链接。我需要将http://www.olddomain.com添加到这些链接的href值中,以确保它们在我的应用程序中仍然能够正常工作。

数据存储在变量text中。

变量text包含:

<p style="text-align: right;">
    Lots of text in here, with all kind of html tags, <br /><br /> 
    when suddenly a link appears:
    <a href="/niceinternalpage.html">Here!</a>
</p>

我需要的输出:

<p style="text-align: right;">
    Lots of text in here, with all kind of html tags, <br /><br /> 
    when suddenly a link appears:
    <a href="www.olddomain.com/niceinternalpage.html">Here!</a>
</p>

提前感谢您!

5个回答

2

在现代浏览器中,您不需要使用jQuery来执行此操作,可以利用document.getElementsByTagName来获取页面上的所有a标签:

// document.getElementsByTagName returns a `NodeList` - it looks like an `Array`
// but lacks all of the methods; so we use `Array.prototype.slice` to turn it
// into a 'real' `Array` so we can filter and loop over it.
aTags = Array.prototype.slice.call(document.getElementsByTagName("a")),
    externalUrl = "http://www.olddomain.com";

// Make use of `filter` to return an Array of all `a` tags whose `href` attribute
// is unqualified (eg: does not start with `http`, again you may wish to make this
// filtering logic more complex).
//
// We then chain a `forEach` call to the result of the `filter` call which prepends
// the `externalUrl` to the `a` tag's `href` attribute.
aTags
    .filter(function (aTag) { 
        return aTag.href.match(/^http/) === null;
    })
    .forEach(function(unqualifiedATag) { 
        var unqualifiedUrl = unqualifiedATag.href;

        // Add a leading forward slash.
        if (unqualifiedUrl.charAt(0) !== "/") {
            unqualifiedUrl = "/" + unqualifiedUrl;
        }

        // Update the aTag's href attribute to fully qualify it.
        unqualifiedATag.href = externalUrl + unqualifiedATag.href;
    }); 

1
+1 对于纯 JavaScript 的答案。但这将更改所有的 a 标签,这在大多数情况下并不是意图(链接到 Facebook/Twitter/等等也会被获取,甚至同一域中的导航链接也会被获取)。 - Pablo Mescher
是的,那是一个合理的批评 ;) filter方法应该更新以确定URL是否合格 - 现在让我们为了好玩来做这个... - JonnyReeves
document.links即使在2000年之前的浏览器中也可以使用,但是过滤和forEach不能在ie8中使用。 - mplungjan

1
你可以使用attr()来更改href的值。

演示

$(variable).find('a').attr('href', function(idx, attrValue){ 
   return 'http://www.olddomain.com' + attrValue;
});

第二个参数是属性的当前值,而不是项目。因此不需要使用 this.href。但是这种优雅的方法值得一赞。 - a better oliver

0
你可以这样做:
var $content = $(text);
$content.find('a').each(function() {
   $(this).attr('href', 'http://www.olddomain.com' + $(this).attr('href') );
});
$content.insertAfter('#elementinyourpage');

我还添加了调用将修改后的内容插入到当前页面的代码。


感谢您发现了错误,我已经修复了,谢谢。 - Nelson
$(this).attr('href') 返回一个值,你不能对它进行赋值。 - a better oliver

0
var uri = $('a').attr('href');
$('a').attr('href', 'www.olddomain.com' + uri);

希望能对你有所帮助。


0
如果您同时拥有内部和外部链接,可以尝试使用正则表达式替换,例如:
$('a').each(function() {
    this.href = this.href.replace(/^\/(.*)/, 'http://www.externaldomain.com/$1');
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接