【问题标题】:How to get a specific node in XML tree with jQuery如何使用 jQuery 获取 XML 树中的特定节点
【发布时间】:2011-05-30 13:22:27
【问题描述】:

我有以下 XML 文件:

<?xml version="1.0" encoding="iso-8859-1"?>
<words>
    <word>
        <id>1</id>
        <name>Teacher</name>
    </word>
    <word>
        <id>2</id>
        <name>Pitcher</name>
    </word>
</words>

还有下面的 jQuery 代码:

$.ajax({
    type: "GET",
    url: "sites.xml",
    dataType: "xml",
    success: function(xml) {
        $(xml).find('word').each(function(){

        ...

});

如何获取 ID == 1 的单词?

这个 ajax 函数在另一个函数中(getWord() 函数)。我想获取任何 ID 的单词并将该值分配给 getWord() 函数的局部变量。

我该怎么做?

【问题讨论】:

    标签: jquery xml


    【解决方案1】:

    您总是可以求助于编写自定义过滤器。

    $(xml).find("word").filter(function () {
      return $(this).find("id").text() == "1";
    }).each(function () {
      console.log(this);
    });
    

    【讨论】:

    • 感谢您的回答。我还有一个问题:我怎样才能得到getWord()父函数中返回的单词。
    • @VansFannel:你不能。将您的后续步骤放入success 回调中。
    【解决方案2】:
    $(xml).find('word').each(function(){
    
           if(parseInt($(this).find('id').text()) == '1')
    {
    
          // your logic here
    }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多