如何使用JQuery选择值为“lastName”的属性“name”的XML元素?

时间:2013-07-11 04:11:50

标签: jquery xml jquery-selectors

我正在尝试使用XML和Javascript(/ jquery)创建一个家谱。我要求用户输入他们的名字,然后我搜索XML文件。我将名称拆分为变量firstName和lastName,然后使用JQuery选择器进行搜索。

正如您在下面看到的,即使我直接将lastName设置为等于字符串“Lawlor”,我也无法通过“family [name = lastName]选择器选择XML元素(由缺失证明)控制台日志,我一直包括在底部。)

下面是XML文件的一部分,然后是我用来选择具有族元素的元素的代码,其中“name”属性等于变量“lastName”。

我做错了什么?

<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:记录处于活动状态 jquery .... 1.0.js(第20行) 你的姓氏是'Lawlor',你的名字是'John'。 familyTree.js(第19行)

1 个答案:

答案 0 :(得分:1)

您需要使用lastNamefirstName是包含要搜索的值的变量

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

演示:Plunker