3

我正在研究一个应用程序女巫从不同的网站获取其内容。在获得的内容中有时是内部链接。我需要将http://www.olddomain.com添加到这些链接的 href 值中,以确保它们仍然可以在我的应用程序中工作。

数据在一个变量中:文本

可变文本包含:

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

提前致谢!

4

5 回答 5

2

您不需要 jQuery 在现代浏览器中执行此操作,您可以使用 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;
    }); 
于 2013-03-23T15:48:06.387 回答
1

您可以使用attr()分配更改的值href

现场演示

$(variable).find('a').attr('href', function(idx, attrValue){ 
   return 'http://www.olddomain.com' + attrValue;
});
于 2013-03-23T15:46:02.803 回答
0

你可以这样做:

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

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

于 2013-03-23T15:44:34.173 回答
0
var uri = $('a').attr('href');
$('a').attr('href', 'www.olddomain.com' + uri);

希望能帮助到你。

于 2013-03-23T15:45:42.770 回答
0

如果您有内部和外部链接,您可以尝试正则表达式替换,如下所示:

$('a').each(function() {
    this.href = this.href.replace(/^\/(.*)/, 'http://www.externaldomain.com/$1');
});
于 2013-03-23T15:50:44.443 回答