【问题标题】:How do I select XML elements with attribute "name" of value "lastName" using JQuery?如何使用 JQuery 选择值为“lastName”的属性“name”的 XML 元素?
【发布时间】:2013-07-09 05:25:10
【问题描述】:

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

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

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

我到底做错了什么?

<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 行)

【问题讨论】:

    标签: jquery xml jquery-selectors


    【解决方案1】:

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

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

    演示:Plunker

    【讨论】:

    • 天哪!非常感谢!我注意到在其他代码行中,选择器将设置为 [attribute=value],而不是 [attribute="value"],但我不知道我必须执行您在上面所做的操作。这种抽象或常见错误是否有名称(假设它很常见)?
    • 我现在明白了。当 lastName 和 firstName 在引号内时,它被“读取”为一个字符串,但在引号之外,它是一个变量。太好了——再次感谢!
    猜你喜欢
    • 1970-01-01
    • 2010-11-02
    • 2012-03-29
    • 2010-12-18
    • 1970-01-01
    • 2012-02-12
    • 2011-07-26
    • 2010-12-17
    相关资源
    最近更新 更多