2011-11-11 7 views
1

제거하거나 숨기려는 반복 된 텍스트가 포함 된 항목이있는 목록이 있습니다. 이에서 그래서 :jQuery를 사용하여 항목 목록에서 반복 단어 제거

<ul class="juicy"> 
<li>Juicy Green Apples</li> 
<li>Juicy Green Tomatoes</li> 
<li>Juicy Green Broccoli</li> 
</ul> 

나는 이것을 달성하고 싶습니다 : 교체하는 텍스트를 미리 알고 있다면

<ul class="juicy"> 
<li>Apples</li> 
<li>Tomatoes</li> 
<li>Broccoli</li> 
</ul> 
+2

항상 같은 텍스트를인가? 또는 텍스트의 중복 된 단어에 대한 일반적인 해결책을 원하십니까? –

+0

예. 단어가 손 앞에 알려질 것입니다. 실제로 제거 할 다른 문자열이있을 수 있습니다. – Seb

답변

1

jQuery의 .text() 방법은 아주 쉽게 처리 할 수 ​​있습니다.

var textToReplace = "Juicy Green", 
    re = new RegExp(textToReplace,"i"); 
$(".juicy li").text(function(index,text){ 
    return text.replace(re,''); 
}); 

편집 : 답변 코멘트에서 질문 :이 같은

뭔가 : 당신은 동적 뭔가를 시도하려는

var textToReplaceArr = ["Juicy Green","Sour Yellow"]; 
for (var i = 0; i < textToReplaceArr.length; i++) { 
    $(".juicy li").text(function(index,text){ 
    var re = new RegExp(textToReplaceArr[i],"i"); 
    return text.replace(re,''); 
    }); 
} 
+0

감사합니다. 이것은 잘 작동합니다. 그 말은 실제로 미리 알려질 것입니다. 동일한 UL에 제거하려는 다른 단어가있는 경우 어떻게됩니까? 나는 단순히 코드를 복제하고 핵심어를 다른 세트로 대체하려고 시도했지만 그 방법이 효과적이다. 좀 더 우아하고 간결한 방법이 있는지 궁금합니다. – Seb

+0

멋진, 감사합니다. 당신은 고용되었습니다;) – Seb

0

를?

$(document).ready(

function() { 
    var repeatedWordsArray = new Array(); 
    var wordsToRemoveArray = new Array(); 
    var i = 0; 
    $($("ul.juicy > li").map(function() { 
     return $(this).text(); 
    }).get().join(" ").split(/\s+/g)).each( //Joins the text of all elements, appends space between them and then splits with space character 

    function() { 
     repeatedWordsArray[this] = repeatedWordsArray[this] == undefined ? 1 : repeatedWordsArray[this] + 1;  //Increments the counter when the same word is encountered 
     if (repeatedWordsArray[this] == 2) {  //If found twice, make a note of the word 
      wordsToRemoveArray[i++] = this; 
     } 
    }); 
    if (wordsToRemoveArray.length > 0) { 
     $("ul.juicy > li").each(
     function() { 
      var ulElement = this; 
      $(wordsToRemoveArray).each(
       function() { 
        var regexp = new RegExp('^\\s*\\w+\\s*$'); 
        if(!$(ulElement).text().match(regexp)) {  //Do not match if the text of element contains a single word with or without spaces at its ends 
         regexp = new RegExp('\\s*' + this + '\\s*','g'); 
         $(ulElement).text($(ulElement).text().replace(regexp, '')); //Set the text of the element after removing the repeatedly found word 
        } 
       } 
       ); 
      } 
     ); 
    } 
} 
); 

이 너무 다음 UL 작동 :

<ul class="juicy"> 
    <li>Juicy Green Apples</li> 
    <li>Juicy Green Tomatoes</li> 
    <li>Juicy Green Broccoli</li> 
    <li>Juicy</li> 
    <li>  Green </li> 
</ul> 
+0

James, 꽤 멋지 네요. 고마워요. 그러나 코드를 사용하려면 제거 할 키워드를 어디에 삽입해야합니까? – Seb

+0

이것을 구현하기 위해 키워드를 추가 할 필요가 없습니다. 이 작업을 수행해야하는 ul 항목의 클래스 이름을 지정하기 만하면됩니다. 여기서 $ ("ul.juicy> li")는 어떤 항목을 적용할지 결정합니다. 'ul.juicy> li'는 '육즙'이라는 이름의 클래스를 가진 'ul'부모 요소 내부의 즉각적인 'li'항목을 의미합니다. 이것은 코드에서 두 번 발생합니다. 이것을 jQuery 선택기로 바꾸면 모든 것이 잘 작동합니다. –

+0

아, 알겠습니다. 자동으로 작동하여 ul에 반복 키워드가 있는지 확인합니다. 감사. 아주 깔끔한. – Seb

관련 문제