[英]Retrieve an HTML element inside of an XML document
I have an XML document with a structure like this: 我有一个具有如下结构的XML文档:
<pod id="1">
Lorem ipsum....
<subpod>
<img src="example.gif">
</subpod>
</pod>
<pod id="2">
Lorem ipsum....
<subpod>
<img src="example2.gif">
</subpod>
</pod>
I have retrieved the XML file through a jQuery $.get()
request, and now I want to embed the images into my document. 我已经通过jQuery
$.get()
请求检索了XML文件,现在我想将图像嵌入到文档中。 This is the code I have tried: 这是我尝试过的代码:
$.get(queryURL, function (data) {
var pods = $(data).find("pod");
if (pods.length !== 0) {
$("#container").html('<div id="podcontainer">' + $(pods[0]).find("img")[0] + $(pods[1]).find("img")[0] + '</div>');
}
});
However, all I get when I run this is 但是,当我运行此命令时,我得到的只是
[object Element][object Element]
[对象元素] [对象元素]
I have also tried turning them into jQuery objects like so: $($(pods[0]).find("img")[0])
, which returns 我还尝试过将它们变成jQuery对象,例如:
$($(pods[0]).find("img")[0])
,该方法返回
[object Object][object Object]
[对象对象] [对象对象]
Using the jQuery $.parseHTML()
function gives 使用jQuery
$.parseHTML()
函数可以
null null
null null
I don't understand why it is doing this, because when I log the elements in the console they show up as valid HTML elements. 我不明白为什么要这么做,因为当我在控制台中记录元素时,它们会显示为有效的HTML元素。
The problem is that you're doing string concatenation: 问题在于您正在执行字符串连接:
$("#container").html('<div id="podcontainer">' + $(pods[0]).find("img")[0] + $(pods[1]).find("img")[0] + '</div>');
...but the elements aren't strings, they're elements . ...但是元素不是字符串,而是元素 。 When you convert an element to a string, you get...
"[object Element]"
. 当您将一个元素转换为字符串时,将获得...
"[object Element]"
。
The solution is: Don't do string concatenation. 解决方案是:不要进行字符串串联。 Here's one way:
这是一种方法:
var div = $('<div id="podcontainer"></div>');
div.append($(pods[0]).find("img"));
div.append($(pods[1]).find("img"));
$("#container").html(div);
Technically, you can do this without the variable: 从技术上讲,您可以在不使用变量的情况下执行此操作:
$("#container").html(
$('<div id="podcontainer"></div>')
.append($(pods[0]).find("img"))
.append($(pods[1]).find("img"))
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.