2011-05-16 5 views
23

que tienen este código HTML en mi página:jQuery.each - Obtención de elementos dentro de una li ul

<div class="phrase"> 
    <ul class="items"> 
     <li class="agap"><ul><li>TEXT1</li></ul></li> 
     <li class="agap"><ul> </ul></li> <!-- empty ul --> 
     <li class="aword">TEXT2</li> 
     .. 
    </ul> 
</div> 

<div class="phrase"> ... </div> 

me gustaría obtener por cada "frase" todos los elementos de "elementos" en una variable de texto, de esta manera:

var string = "TEXT1 - BLANK - TEXT2"; 

Actualmente tengo este código javascript:

<script> 
$(function() { 
    $('.phrase .items').each(function(){ 
     var myText = ""; 

     // At this point I need to loop all li items and get the text inside 
     // depending on the class attribute 

     alert(myText); 

    }); 
}; 
</script> 

¿Cómo puedo recorrer todo el interior <li>.items?

Estaba probando diferentes maneras pero no obtuve buenos resultados.

Respuesta

43

En primer lugar creo que debe arreglar sus listas, como el primer nodo de un <ul> debe ser un <li> (stackoverflow ref). Una vez que es la configuración, puede hacer esto:

// note this array has outer scope 
var phrases = []; 

$('.phrase').each(function(){ 
     // this is inner scope, in reference to the .phrase element 
     var phrase = ''; 
     $(this).find('li').each(function(){ 
      // cache jquery var 
      var current = $(this); 
      // check if our current li has children (sub elements) 
      // if it does, skip it 
      // ps, you can work with this by seeing if the first child 
      // is a UL with blank inside and odd your custom BLANK text 
      if(current.children().size() > 0) {return true;} 
      // add current text to our current phrase 
      phrase += current.text(); 
     }); 
     // now that our current phrase is completely build we add it to our outer array 
     phrases.push(phrase); 
    }); 
    // note the comma in the alert shows separate phrases 
    alert(phrases); 

Trabajando jsfiddle.

Una cosa es que si obtienes el .text() de un nivel superior li obtendrás todo el texto de nivel secundario con él.

Al mantener una matriz, se pueden extraer muchas frases múltiples.


EDIT:

Esto debería funcionar mejor con un vacío UL sin LI:

// outer scope 
var phrases = []; 

$('.phrase').each(function(){ 
    // inner scope 
    var phrase = ''; 
    $(this).find('li').each(function(){ 
     // cache jquery object 
     var current = $(this); 
     // check for sub levels 
     if(current.children().size() > 0) { 
      // check is sublevel is just empty UL 
      var emptyULtest = current.children().eq(0); 
      if(emptyULtest.is('ul') && $.trim(emptyULtest.text())==""){ 
       phrase += ' -BLANK- '; //custom blank text 
       return true; 
      } else { 
      // else it is an actual sublevel with li's 
      return true; 
      } 
     } 
     // if it gets to here it is actual li 
     phrase += current.text(); 
    }); 
    phrases.push(phrase); 
}); 
// note the comma to separate multiple phrases 
alert(phrases); 
+0

Esta es la mejor solución. Buen trabajo :) – MarioRicalde

+0

Esto funciona para mí, pero necesito saber cuándo no tiene li, así que, en este caso, debería poner "EN BLANCO" como texto. Tal vez mi publicación no estaba clara en absoluto. No entiendo esta línea: if (current.children(). Size()> 0) {return true;} Gracias por su respuesta. – rusben

+0

Bueno, eso técnicamente no es válido. Pero puedes trabajar con eso usando esa línea. Actualizaré mi respuesta con algunos comentarios aclaratorios: ¡ahora está actualizada! – WSkid

7
$(function() { 
    $('.phrase .items').each(function(i, items_list){ 
     var myText = ""; 

     $(items_list).find('li').each(function(j, li){ 
      alert(li.text()); 
     }) 

     alert(myText); 

    }); 
}; 
Cuestiones relacionadas