2015-10-16 53 views
0

我是jquery的新手,我有一个xml文档,我希望ajax只显示一个记录(容器),而不是显示所有其他记录(容器)。目前,其显示的所有记录,而不是我想它在代码中显示一个例如问题2.从jQuery检索单个记录ajax

XML文件

<?xml version="1.0" encoding="UTF-8"?> 
<container> 
<record> 
<code>1</code> 
<question>what is your name</question> 
</record> 
<record> 
<code>2</code> 
<question>what is your day</question> 
</record> 
</container> 

阿贾克斯

$.ajax({ 
    url:'my.xml', 
    dataType:'xml', 
    success: function(data){ 


     function question(e) 
     { 

       $(data).find('container record').each(function() 
       { 
       var code = $(this).find('code').text(); 
       if (code == 2) 
       { 
        var record = $(this).find('question').text(); 
        $('.timeline').append($('<P />',{text:record})); 
       } 
       else 
       { 

        $('.timeline').append($('<P />','')); 
       } 


       }); 

     } 
     question(); 
    }, 
    error: function(){ 
     $('.timeline').text('Failed to read feed'); 
    } 
}); 

HTML

<div class="timeline"> 

</div> 
+0

如果您只需要一个,则需要定义用于过滤该标准的条件 – charlietfl

回答

0

您可以使用:eq()选择器:

$.ajax({ 
    url:'my.xml', 
    dataType:'xml', 
    success: function(data){ 
     function question(no) { 
      var $record = $(data).find('record:eq('+no+')'); 
      if ($record.find('code').text() == '2') { 
       $('.timeline').append($('<P />', {text: $record.find('question').text() })) 
      } else { 
       $('.timeline').append($('<P />','')); 
      } 
     } 
     question(0); //1, 2, 3 and so on 
    }, 
    error: function(){ 
     $('.timeline').text('Failed to read feed'); 
    } 
});