0

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

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

下面是 XML 文件的一部分,后面是我用来选择具有 family 元素的元素的代码,其中“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 行)

4

1 回答 1

1

您需要使用 aslastNamefirstNameare 保存要搜索的值的变量

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

演示:Plunker

于 2013-07-11T04:17:23.020 回答