2013-07-11 51 views
0

我想创建一个使用XML和Javascript(/ jquery)的家族树。我要求用户输入他们的名字,然后我搜索XML文件。我将名称分割为变量firstName和lastName,然后使用JQuery选择器进行搜索。如何使用JQuery选择具有值“lastName”的属性“name”的XML元素?

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

XML文件的一部分在下面,后面跟着我用来选择元素的代码, “name”属性等于变量“姓氏”。

什么弗兰克•我做错了?

<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(line 20) 您的姓氏是'Lawlor',您的名字是'John'。 familyTree.js(19行)

回答

1

您需要使用的lastNamefirstName是保持该值的变量进行搜索

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

演示:Plunker

+0

@mplungjan由于错过了 –

+0

我的天啊!非常感谢!我注意到,在其他代码行中,选择器将设置为[attribute = value],而不是[attribute =“value”],但我不知道我必须要做什么是否有这种抽象或常见错误的名称(假设它很常见)? – johnklawlor

+0

我现在看到了。当lastName和firstName在引号内时,它以字符串形式“读取”,但在引号之外,它是一个变量。很好 - 再次感谢! – johnklawlor

相关问题