Javascript 儿童';XML中的子对象
我有一个简单的XML文件,它由下面发布的脚本加载到页面上。它从字符串转换为XML文件没有任何问题,但使一切复杂化的是,我无法访问孩子的孩子 我想知道为什么我的代码不起作用,我应该怎么做才能得到标签名Javascript 儿童';XML中的子对象,javascript,jquery,html,xml,dom,Javascript,Jquery,Html,Xml,Dom,我有一个简单的XML文件,它由下面发布的脚本加载到页面上。它从字符串转换为XML文件没有任何问题,但使一切复杂化的是,我无法访问孩子的孩子 我想知道为什么我的代码不起作用,我应该怎么做才能得到标签名 function load_xml() { $.ajax({ type: "GET", url: "file.xml", dataType: "xml", success: function (xmlData) {
function load_xml() {
$.ajax({
type: "GET",
url: "file.xml",
dataType: "xml",
success: function (xmlData) {
var $first_child = $(xmlData).children()[0];
var first_name = $first_child.nodeName; // returns a proper name of a node
var $second_child = $first_child.children()[0]; // doesn't work
var $second_name = $second_child.nodeName; // returns nothing (don't know why)
},
error: function () {
alert("Could not retrieve XML file.");
}
});
}
在您的情况下,
$first\u child
不是jQuery集合。您需要用$()
包装它。这是一个正确的版本
var first_child = $(xmlData).children()[0]; // [0] actually returns the first "raw" node
var first_name = first_child.nodeName;
var $first_child = $(first_child);
var second_child = $first_child.children()[0];
var second_name = second_child.nodeName;
非常感谢-你的回答对我非常有用:)。然而,我认为有一件事应该在你的解决方案中得到纠正。要遵循命名约定,应该编写第二个\u子对象和第二个\u名称,而不是$second\u子对象和$seocond\u名称(据我正确理解,这些变量不是jQuery对象)。