javascript - 更改变量中的链接

标签 javascript jquery ajax

我有一个变量(通过 AJAX 加载),其中包含一段 HTML 文档(但不是包含 html、head 和 body 的整个文档。

我想这样改变它:

For each links in this variable that points to the same domain add class 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>

最佳答案

问题是 anchor 是根元素,find() 只能查找子元素。

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

因此 $(html).find('a') 不起作用,因为 anchor 不是子节点。

您可以使用 filter() 来代替,但这只能获取根元素,并且如果您同时拥有根元素和子元素,如果会失败,

试试这样

var div = $('<div />').html(html); 

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

这会创建一个新的父元素,因此您可以确定,一旦内容附加到容器元素,html 中的任何 anchor 都将成为子元素。

关于javascript - 更改变量中的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23969787/

相关文章:

javascript - javascript中的正则表达式,仅匹配A-z和_?

javascript - 使用 jQuery 修复无效的嵌套列表

jquery - 完整日历以明智的方式显示所有员工的约会列

javascript - 如何通过添加 for 循环来遍历 data.games 来重写搜索函数,并在搜索时添加它显示的分数?

javascript - 计算文本区域/输入框中的字符数的优雅方法

javascript - 将 CSS `backdrop-filter` 应用于多边形形状

javascript - 自从用 on() 替换 live() 后,remove() 出现问题

javascript - 有没有办法用包含 ENTER 键换行符的 SQL 数据填充文本区域表单?

php - 通过JSON、Jquery和PHP动态显示MYSQL表数据

java - 如何使用Servlet和Ajax?