我有一个变量(通过 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/