Javascript 从 id 获取信息

Javascript get information from id

本文关键字:信息 获取 id Javascript      更新时间:2023-09-26

所以我有这个XML:

<?xml version="1.0" encoding="UTF-8"?>
<products>
<product top-level-category="cat" sub-level-category="cat-sub">
    <id>235</id>
    <title>title</title>
    <brand>brand 1</brand>
    <price>200.00</price>
    <description>This is my amazing description</description>
    <spec>
        <s1>24.2</s1>
        <s2>23.5 x 15.6 CMOS</s2>
        <s3>Auto, 100-12800</s3>
        <s4>Nikon F Mount</s4>
    </spec>
</product>
<products>

如何通过仅拥有产品的 ID 来获取标题、品牌、价格、s1、s2、s3、s4 等?

我当前失败的尝试:

$(productsDomTree).each(function() {
                    var name = $(this).find('id').text();
                    if (name = vars['id']) {
                        alert(name);
                    }
                });

所有这些都告诉我它找到了正确的元素

更新了有效的代码,但始终选择第二个:

var id = vars['id'];
                alert(id);
                var ids = ($products).find('id');
                var id = ids.filter(function(id) { return !!$(this).text() == id; });
                var product = id.parent();
                var title = product.find( "title" ).text();
                alert(title);

如果你将 xml 字符串输入 jQuery 的 parseXML 函数,则可以完成此操作:

var id = 235;
var xml = "Your XML Here!";
var xmlDoc = $.parseXML( xml );
var $xml = $( xmlDoc );
var ids = $xml.find('id');
var id = ids.filter(function(id) { return !!$(this).text() == id; });
var product = id.parent();
var title = product.find( "title" ).text();

CSS 选择器无法访问元素的文本内容。然后,我推荐XPath,例如

var xmlString = '<?xml version="1.0" encoding="UTF-8"?><products><product top-level-category="cat" sub-level-category="cat-sub"><id>235</id><title>title</title><brand>brand 1</brand><price>200.00</price><description>This is my amazing description</description><spec><s1>24.2</s1><s2>23.5 x 15.6 CMOS</s2><s3>Auto, 100-12800</s3><s4>Nikon F Mount</s4></spec></product></products>';
var doc = new DOMParser().parseFromString(xmlString, "text/xml");
var iterator = doc.evaluate('//product[id = "235"]/*', doc, null, XPathResult.ANY_TYPE, null);
var obj = {}, val;
while (val = iterator.iterateNext())
  obj[val.nodeName] = val.textContent;
document.write('<pre>' + JSON.stringify(obj, null, 2) + '</pre>');