改变变量中的链接

Changing links in variable

本文关键字:链接 变量 改变      更新时间:2023-09-26

我有一个变量(通过AJAX加载),它包含一段HTML文档(但不是整个文档的HTML,头部和正文)。

我想这样修改:

对于该变量中指向相同域的每个链接添加类internal_link。

对于过滤整个文档中的链接,我使用如下示例:

$('a').filter(function() {
        return this.hostname && this.hostname === location.hostname;
    }).addClass('internal_link');

它工作起来没有任何问题。但是我不知道如何在整个文档上使用这些代码,而是如何在变量上使用这些代码来改变它的值。

我试过下面的代码:

html = data.content;
alert(html);
$(html).find('a').filter(function() {
    return this.hostname && this.hostname === location.hostname;
}).addClass('internal_link');
alert (html);

但它似乎不起作用。当我运行第二个警报时,internal_link类不在html中。

怎么做呢?

示例页面脚本:

<html>
<head>
    <script src="jquery-1.11.1.min.js"></script>
</head>
<body>
<script>
    $().ready(function() {
        html = '<a href="http://localhost">test</a>';
       alert(html);
        $(html).find('a').filter(function() {
            return this.hostname && this.hostname === location.hostname;
        }).addClass('internal_link');
        alert (html);

    });
</script>
</body>
</html>

问题是锚是根元素,find()只找到子元素。

html = '<a href="http://localhost">test</a>';

所以$(html).find('a')不会工作,因为锚不是一个孩子。

您可以使用filter()代替,但这将只有获得根元素,如果您同时拥有根元素和子元素,则会失败,

像这样试试

var div = $('<div />').html(html); 
div.find('a').filter(function() {
    return this.hostname && this.hostname === location.hostname;
}).addClass('internal_link');

创建一个新的父元素,所以您可以确定html中的任何锚将是一个子元素,一旦内容被附加到容器元素。

$(html)不是html标记中的对象。请确保您要查找的代码是标记的一部分。

使用下面的设置可以工作:

$('html').find('a').filter(function() {
    return this.hostname && this.hostname === location.hostname;
}).addClass('internal_link');

除此之外,您还可以启动文档准备上的完整函数,以确保您的标记已加载:

$(document).ready(function(){
    $('html').find('a').filter(function() {
        return this.hostname && this.hostname === location.hostname;
    }).addClass('internal_link');
});