2009-11-14 20 views
7

come un ciclo su tutti i tag in un xmlJquery - scorrere tutti i tag XML

ho un php che genera XMLs come il prossimo

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

in modo che ricevo questo xml (questo funziona bene)

$.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? 

    });  

}}); 

risposta

3

Si vorrà esaminare la funzione children(), tra gli altri. Vedi lo jQuery traversal documentation per maggiori informazioni sulle funzioni.

+0

grazie per la tua asnwer veloce, ma ancora non posso fare è = ((e IM triste ...) nella guida jquery dice var $ kids = $ (e.target) .children(); ma ancora .. che mi dà un po 'di oggetto/array con i childs ma come ottengo il tagName di ogni bambino? questo non ha funzionato $ (questo) .children(). Each (function() {alert ($ (this) .tagName);}); // non ha funzionato questo né, mostra tutti i metodi/att var childs = $ (this) .children(); \t per avviso (chiave in childs) (chiave); – dedoz

+3

finalmente .. var $ childs = $ (this) .children(); var length = $ childs.length; while (length--) alert ($ childs [length] .tagName); grazie mille – dedoz

11

Questo link fornisce un buon esempio per l'utilizzo di iterazione attraverso 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

Problemi correlati