2011-05-16 4 views
23

내부 얻기 리 요소는 내 페이지에서이 HTML을 이 같은 :jQuery.each 상향 링크

var string = "TEXT1 - BLANK - TEXT2"; 

나는 현재이 자바 스크립트 코드가 : 나는 모든 <li> 01 내에서 반복 할 수있는 방법

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

을?

다른 방법을 시도했지만 좋은 결과를 얻지 못했습니다.

답변

43

먼저 난 당신이 <ul>의 첫 번째 노드가 <li> (stackoverflow ref)가되어야하므로, 귀하의 목록을 수정해야합니다 생각합니다. 설정이 완료되면 다음을 수행 할 수 있습니다.

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

Working jsfiddle.

상위 레벨의 .text()을 얻는다면, 모든 하위 레벨 텍스트를 얻게 될 것입니다.

배열을 유지하면 여러 구를 추출 할 수 있습니다.


편집 :

이 더 LI와 빈 UL 더 잘 작동합니다 :

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

이 가장 좋은 솔루션입니다. 좋은 직장 :) – MarioRicalde

+0

이것은 나를 위해 일하고있다. 그러나 나는 ul이 없다면 알아야한다. 그래서이 경우 나는 "BLANK"를 텍스트로 받아야한다. 어쩌면 내 게시물이 전혀 분명하지 않을 수도 있습니다. 이 줄을 이해할 수 없다 : if (current.children(). size()> 0) {return true;} 답장을 보내 주셔서 감사합니다. – rusben

+0

음, 기술적으로 유효한 마크 업이 아닙니다. 그러나 그 라인을 사용하여 작업 할 수 있습니다. 몇 가지 명확한 설명으로 답변을 업데이트하겠습니다 - 이제 업데이트되었습니다!. – 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); 

    }); 
};