gpt4 book ai didi

javascript - 奇怪的 jQuery XML 问题

转载 作者:行者123 更新时间:2023-11-29 18:35:04 25 4
gpt4 key购买 nike

我在 XML 文档中有一个引号列表。每个引号都是这样包装的:

<Item>
<Quote>This is a quote!</Quote>
<Source>-- this is the Source of the Quote!</Source>
</Item>

这是 jQuery:

    var html = '';
var tmpl = '<li class=""><p class="quote">__quote</p><p class="source">__source</p></li>';

$(quoteObj).find('Item').each(function(){

$that = $(this);

var _quote = $that.children('Quote').text();
var _source = $that.children('Source').text();

var qhtml = tmpl.replace('__quote', _quote).replace('__source', _source);

html += qhtml;

});

return html;

在最终产品中,QUOTES都在那里,但是SOURCES不是。我一辈子都想不通为什么。我看不见的东西就在我面前?

回答评论的附加信息:

  1. XML 格式正确,我在上面对其进行了更改。
  2. 我添加了 var tmpl行来显示我在循环中替换的内容。 __quote正在被替换,__source至少正在采取行动,因为第二个<p>是空的,而不是包含一个字符串。
  3. 我已经检查了从 AJAX 调用返回的实际 XML,它就在那里,因为它应该在。

在我看来,这是范围界定和 this 的某种问题,或使用 .children() 的操作方法,但我还是找不到。

最后一点:

将 XML 标记大小写更改为 Initial Caps,它在相关文档中。

最佳答案

jQuery 不解析 XML。将 XML 字符串传递给 $() 只是将该字符串指定为元素的 innerHTML 属性,这会产生可变且不可预测的结果。您需要自己解析 XML,使用浏览器内置的 XML 解析器,然后将生成的文档传递给 jQuery:

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 xmlStr = "<Item><Quote>This is a quote!</Quote><Source>-- this is the Source of the Quote!</Source></Item>";

var xmlDoc = parseXml(xmlStr);
$xml = $(xmlDoc);

$xml.find('Item').each(function() {
// Do stuff with each item here
alert("Item");
});

关于javascript - 奇怪的 jQuery XML 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4111881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com