我正在尝试使用 ajax 加载 XML 文件并将该 XML DOM 文档的部分内容插入到浏览器 HTML DOM 中。
到目前为止,这有效,但是当我尝试使用 jquery 获取带有类或 id 选择器的插入元素时,它返回空列表。
到目前为止我只在 Firefox 10 中尝试过。有谁知道为什么会这样吗?这样做是不是不安全?
测试.html:
<html><head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<title>dom test</title>
<script type="text/javascript">
$(function() {
var xml = null;
$.ajax({
type : "GET",
async : false,
url : 'test.xml',
dataType : "xml",
success : function(data) {
xml = data;
}
});
$('body').html($(xml).children().clone());
console.log($('h1')); // prints the h1 element
console.log($('.title')); // prints empty list
console.log($('p')); // prints the p element
console.log($('#content')); // prints empty list
});
</script>
</head><body></body></html>
测试.xml:
<div id="root">
<h1 class="title">Blabla</h1>
<p id="content">
Lorem ipsum
</p>
</div>
最佳答案
看起来您只是想通过 AJAX 获取 HTML,然后将其插入到您的页面中。为此,您应该在 ajax 请求中使用 dataType: "html"
。
$(function() {
var html = null;
$.ajax({
type : "GET",
async : false,
url : 'test.xml',
dataType : "html",
success : function(data) {
html = data;
}
});
$('body').html(html);
});
关于javascript - 将 XML 插入 DOM 会导致类/id 选择器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9193752/