jQuery和XML问题 [英] jquery and xml issue
问题描述
我有一些xml
<entry>
<a>a</a>
...
<subelement>
<b>b</b>
....
</subelement>
</entry>
如果我这样做$(entry).find('whatIAmLookingFor')
if I do $(entry).find('whatIAmLookingFor')
当这些元素嵌套在子元素中时,它适用于某些元素,但不适用于其他元素.
it works for some elements, but not for other elements, when those elements are nested in the subelement.
我可以做到这一点
$(entry).find('subelement').children()[indexofwhatiamlookingfor].textContent;
在Firebug中,但显然这是一个hack ...
in Firebug, but obviously this is a hack...
为什么要找到"子元素中的某些元素,而不能找到其他元素?我让另一位开发人员研究了此问题,以确保元素名称正确(没有发指的问题).
Why would 'find' find some elements in a subelement but not others? I had another developer look at this to make sure I had the element names correct (no fat finger issues).
推荐答案
jQuery无法解析XML.您可以使用以下简单函数来执行此操作,并使用jQuery在文档上执行其通常的查询工作:
jQuery doesn't parse XML. You can use the following simple function to do it and use jQuery to do its usual querying stuff on the document:
var parseXml;
if (window.DOMParser) {
parseXml = function(xmlStr) {
return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
};
} else if (typeof window.ActiveXObject != "undefined" &&
new window.ActiveXObject("Microsoft.XMLDOM")) {
parseXml = function(xmlStr) {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlStr);
return xmlDoc;
};
} else {
parseXml = function() { return null; }
}
var xml = parseXml("<foo>Stuff</foo>");
if (xml) {
var $xmlDoc = $(xml);
window.alert($xmlDoc.find("foo")[0].nodeName);
}
这篇关于jQuery和XML问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!