简体   繁体   English

使用jQuery从XML获取父节点

[英]Get Parents Node From XML using jQuery

i have a XML file 我有一个XML文件

<?xml version="1.0" encoding="ISO-8859-1"?>
<childrens>
 <child id="1" value="Root Catalog" parent_id="0">
  <child id="2" value="Apparel" parent_id="1">
    <child id="3" value="Accessories" parent_id="2">
        <child id="4" value="Handbags" parent_id="3">
            <child id="5" value="Jewelry" parent_id="4"/>
        </child>
    </child>
  </child>
 </child>
</childrens>

i want to find parents upto particular element 我想找到特定元素的父母

i have written this code 我已经写了这段代码

which returns me all the parents 这让我所有的父母

$(document).ready(function(){
$.ajax({
    type: "GET",
    url: "test.xml",
    dataType: "xml",
    success: function(xml) {
        $(xml).find('child[value="test"]').parents().each(function(){
            var i = $(this).attr('value');
            alert(i);
        });
    }
});
});

i want parents up to where id=2 and value=Apparel 我希望父母在id=2value=Apparel

if i use .parents('[value="Apparel"]') then it will returns only one name that is Apparel 如果我使用.parents('[value="Apparel"]')则它将仅返回一个名称,即Apparel

You could use parentsUntil for this: 您可以为此使用父母

$(xml).find('child[value="test"]').parentsUntil('[value="Apparel"]').each( ...

From the docs: 从文档:

Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. 获取当前匹配元素集中每个元素的祖先,直到但不包括选择器,DOM节点或jQuery对象匹配的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM