Javascript 在变量中更改链接
我有一个变量(通过AJAX加载),它包含一段HTML文档(但不是包含HTML、head和body的整个文档) 我想这样做: 对于此变量中指向同一域的每个链接,添加 类内部链接 用于过滤整个文档中的链接,例如:Javascript 在变量中更改链接,javascript,jquery,ajax,Javascript,Jquery,Ajax,我有一个变量(通过AJAX加载),它包含一段HTML文档(但不是包含HTML、head和body的整个文档) 我想这样做: 对于此变量中指向同一域的每个链接,添加 类内部链接 用于过滤整个文档中的链接,例如: $('a').filter(function() { return this.hostname && this.hostname === location.hostname; }).addClass('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>
$().ready(函数()){
html='';
警报(html);
$(html).find('a').filter(函数(){
返回this.hostname&&this.hostname==location.hostname;
}).addClass(“内部链接”);
警报(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');
});
问题是锚点是根元素,
find()
只查找子元素
html = '<a href="http://localhost">test</a>';
这将创建一个新的父元素,因此您可以确定,
html
中的任何锚点在内容附加到容器元素后都将是子元素。以及data.content
是什么样子的?锚点是根元素吗?我为问题添加了简单的测试脚本,非常感谢。这正是我所需要的。
var div = $('<div />').html(html);
div.find('a').filter(function() {
return this.hostname && this.hostname === location.hostname;
}).addClass('internal_link');