Подтвердить что ты не робот

JQuery.each - Получение элементов li внутри ul

У меня есть этот HTML-код на моей странице:

<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>

Я хотел бы получить для каждой "фразы" все элементы в "элементах" в текстовой переменной, например:

var string = "TEXT1 - BLANK - TEXT2";

В настоящее время у меня есть этот код 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>

Как я могу повторить все <li> внутри .items?

Я пытался разными способами, но я не получил хороших результатов.

4b9b3361

Ответ 1

Сначала я думаю, вам нужно исправить свои списки, так как первый node <ul> должен быть <li> (fooobar.com/questions/224089/...). После этого вы можете сделать это:

// 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);

Работа jsfiddle.

Одно дело, если вы получите .text() верхнего уровня li, вы получите весь текст суб-уровня.

Сохранение массива позволит извлечь много разных фраз.


EDIT:

Это должно работать лучше с пустым UL без 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);

Ответ 2

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

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

        alert(myText);

    });
};