Javascript XML loading jQuery



我使用 jQuery 将 XML 数据加载到 javascript 时遇到问题。

我这里有一个 xml:

<config>
<device>
    <node>1</node>
    <name>Block</name>
    <description>Block in saloon</description>
    <area>Salon</area>
</device>   
<device>
    <node>2</node>
    <name>Line</name>
    <description>Lottr</description>
    <area>Living room</area>
</device>   
</config>   

我想找到节点 = 2 的设备名称。

这是我的代码:

       $.ajax({
         type: "GET",
         url: "config2.xml",
         dataType: "xml",
         success: function(xml) {
            var kurs = $(xml).find('name').text();
            alert(kurs);
         }
   });

我应该在var kurs中放什么?

$(document).ready(function () {
  $.ajax({
    type: "GET",
    url: "config2.xml",
    dataType: "xml",
    success: function (xml) {
      $(xml).find('device').each(function () {
        var node = $(this).find('node');
        if (node.text() == '2') {
          name = $(this).find('name').text();
        }
      });
    }
  });

});

var myVal;
$(xml).find('node').each(  //find the node and loop through them
    function(){
        var node = $(this);  
        if (node.text==="2") {   //see if the node's value is 2
            myVal = node.siblings("name").text();  //find the sibling name element
            return false;  //exit the each loop
        }
    }
);
console.log(myVal);

类似于这个问题:jQuery在XML中获取匹配的节点

我认为这样的事情应该有效:

$.ajax({
     type: "GET",
     url: "config2.xml",
     dataType: "xml",
     success: function(xml) {
        //this should get you the device node 
        var $kurs = $(xml).find('node:contains("2")').parent();
        //this should get you the name from the device node
        var name = $kurs.find('name'); 
     }
}); 

最新更新