2009-11-14 23 views
7

cómo bucle sobre todas las etiquetas en un xmlJquery - iterar a través de todas las etiquetas XML

tengo un php que genera XMLs como la siguiente

<register> 
    <name>peter</name> 
    <age>12</age> 
</register> 
<register> 
    <name>mary</name> 
    <age>20</age> 
</register> 

por lo que recibo este XML (esto funciona bien)

$.ajax({success: function(xml) { 

    $(xml).find('register').each (function() 
    { 
    alert($(this).find('name').text()) // works fine, shows peter then mary on the next loop of "each" 



    // But if i dont know the tag names (name,age) for each register ?  

    // Something like 

     $(this).nodes().each .... // 
alert($(this).tagName); // i wanna show "name" & "age", how can i get the tag names inside each register in my xml sample tree? 

    });  

}}); 

Respuesta

3

Tendrá que mirar la función children(), entre otros. Consulte jQuery traversal documentation para obtener más información sobre las funciones.

+0

gracias por su asnwer rápido pero todavía no puedo hacerlo = ((e IM triste ...) en la ayuda de jquery dice var $ kids = $ (e.target) .children(); pero todavía ... que prolly me da algún objeto/matriz con los hijos pero ¿cómo obtengo el tagName de cada uno de los hijos? esto no funcionó $ (esto) .children(). Each (function() {alert ($ (this) .tagName);}); // no funcionó esto tampoco, muestra todos los métodos/att var childs = $ (this) .children(); \t para (clave en niños) alerta (clave); – dedoz

+3

finalmente ... var $ childs = $ (this) .children(); var longitud = $ childs.length; while (length--) alerta ($ childs [longitud] .tagName); muchas gracias – dedoz

11

Este enlace proporciona un buen ejemplo para el uso de la iteración a través de XML

xml.find('result').find('permissionDetails').each(function(){ 
    $(this).children().each(function(){ 
     var tagName=this.tagName; 
     var val=$(this).text(); 
     if(val==1){ 
      $('input:checkbox[name='+tagName+']').attr('checked',true); 
     } 
     else if(val==0){ 
      $('input:checkbox[name='+tagName+']').removeAttr('checked'); 
     } 
    }) 
}); 

http://anasthecoder.blogspot.in/2012/02/looping-through-xml-with-jquery.html

Cuestiones relacionadas