Jquery Find an XML element based on the value of one of it's children

后端 未结 1 1288
不思量自难忘°
不思量自难忘° 2021-01-14 13:58

I\'m working on a simple XML phonebook app to learn JQuery, and I can\'t figure out how to do something like this: When the user enters the first name of a contact in a text

相关标签:
1条回答
  • 2021-01-14 14:40

    Well, I'm not sure how you want to choose the <person> or how you want to display the result, but this example will find Evelyn, and place the related info into a variable;

    var myXML; 
    
    function searchXML(){
      $.ajax({
         type:"GET",
         url: "phonebook.xml",
         dataType: "xml",
         success: function(xml){
                  // Filter Evelyn out of the bunch
                myXML = $(xml).find("person").filter(function() {
                    return $(this).find('first_name').text() == "Evelyn";
                });
    
                  // Store a string with Evelyn's info in the display variable
                var display = myXML.children().map(function() {
                    return this.tagName + '=' + $(this).text();
                }).get().join(' ');
    
                  // alert the result
                alert(display);
            }
      });
    }
    searchXML();
    

    EDIT:

    When you say that you want to "return" the <person>, be aware that you can't simply return it as you would in a regular function. The rest of your code has likely finished executing before the AJAX response was received, so any attempt to access the <person> in the myXML variable will result in a value of undefined.

    Instead, you need to perform whatever manipulation you want inside the success callback, or you need to place it inside another function, and call that function from within the success callback.

    The example I gave does the work inside.

    I'm still not sure how it is that you want to select which person, though. If you wanted to operate on each one, then you would do so in a loop. For example, you could use:

    $(xml).find("person").each(function() {
        // do your processing...
    });
    
    0 讨论(0)
提交回复
热议问题