简体   繁体   中英

How do I select XML elements with attribute “name” of value “lastName” using JQuery?

I'm trying to create a family tree using XML and Javascript (/jquery). I ask for the user to input their name, and then I search the XML file. I split the name into variable firstName and lastName, and then search using a JQuery selector.

As you can see below, even after I've directly set lastName to equal the string "Lawlor", I am not able to select the XML element via the "family[name=lastName] selector (as evidenced by the missing console log, which I've included all the way at the bottom).

A portion of the XML file is below, followed by the code I'm using to select the elements which have a family element in which the "name" attribute is equal to the variable "lastName".

What the frack am I doing wrong?

<xml id="familyTree" class="hidden">
<generation0>
    <family name="Lion" surname= "DT" children="4">
        <father>Joe</father>
        <mother>Schmoe Rose</mother>
        <child>Lu</child>
        <child>Bob</child>
        <child>Sam</child>
        <child>Dick</child>
    </family>
    <family name="Lawlor" surname="JR" children="5">
        <father>JK</father>
        <mother>Tulip</mother>
        <child>Holden</child>
        <child>Ewell</child>
        <child>Boo</child>
        <child>Scout</child>
        <child>John</child>
    </family>
           ...

$("input#submitButton").click( function () {
    name  = $("input#txtField")[0].value;
    var firstName = name.split(" ")[0];
    var lastName = "Lawlor";
    console.log("Your last name is '"  + lastName + ",' and your first name is '" + firstName + ".'");

    $.ajax({
        url: 'familyTree.xml',
        type: "GET",
        dataType: "xml",
        success: function(xml) {
            $(xml).find("family[name=lastName] child:contains(firstName)").each(function() {
                console.log("what the FRACK?!");                    
            })
        },
        error: function(XMLHttpRequest, textStatus, errorThrow) {
            alert('Data could not be loaded - ' + textStatus);
        }
    });
})

JQMIGRATE: Logging is active jquery....1.0.js (line 20) Your last name is 'Lawlor,' and your first name is 'John.' familyTree.js (line 19)

You need to use as lastName and firstName are variables which holds the value to be searched

        $(xml).find("family[name=" + lastName + "] child:contains(" + firstName + ")").each(function() {
            console.log("what the FRACK?!");                    
        })

Demo: Plunker

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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