2009-05-19 2 views
2

JavaScript를 사용하여 <div> 태그를 HTML 페이지의 단어 주위에 추가 할 수 있는지 궁금합니다.콘텐츠 주위에 HTML 태그를 추가하는 JavaScript

나는 HTML 파일 집합을 검색하고 키워드가 들어있는 파일 목록을 반환하는 JS 검색을 사용합니다. 동적으로 추가 할 수 있도록하고 싶습니다 div class = "highlight"> 키워드를 두드러지게 나타냅니다.

대체 검색을 수행하는 경우 원본 <div>을 제거하고 새 항목을 추가해야합니다. 누구라도 이것이 가능한지 알고 있습니까?

모든 팁이나 제안은 정말 감사하겠습니다.

건배,

로리.

답변

0

포장은 jQuery 꽤 간단하다

다음
$('span').wrap('<div class="highlight"></div>'); // wraps spans in a b tag 

는 다음과 같이 뭔가를 제거 : 당신은하지만, 일부 문자열 분할을해야 할 것 같은

$('div.highlight').each(function(){ $(this).after($(this).text()); }).remove(); 

이 소리 때문에 포장 할 수있다 일부 태그 (예 : span)로 모든 단어를 미리 감싸고 싶지 않으면 작동하지 않습니다.

+0

여기서 문제는 당신이 그렇게이 그렇게 쉽지 않을 수 있습니다 강조해야 할 키워드를 제공하는 선택을하지 않아도됩니다. 단락의 중간에있는 단어 하나를 선택하고 태그로 둘러 쌀 필요가 있습니다. –

0

DOM API는이를 쉽게 수행 할 수있는 방법을 제공하지 않습니다. 내가 아는 한 최선의 해결책은 텍스트를 JavaScript로 읽는 것입니다. replace을 사용하여 원하는 내용을 변경하고 전체 내용을 다시 작성하십시오. 한 번에 하나의 HTML 노드에서이 작업을 수행하거나 <body> 전체를 한 번에 수정할 수 있습니다.

$('body').html($('body').html().replace(/(pretzel)/gi, '<b>$1</b>')); 
+1

그런 접근법에주의하십시오. 대체 표현식은 html 수준에서 작동하므로 누군가가 'table'을 강조 표시하려고하면 html이 엉망이됩니다. –

0

그냥 모든 것을 포장과 같은 선택을 쓸 수 없습니다 : 여기

그 jQuery를 작동하는 방법입니까?

$('div.bar').each(function(){ $(this).after($(this).text()); }).remove(); 

편집 : 두 번째 생각에, 첫 번째 문은 div 태그가 아닌 유일한 단어 요소를 포장 할 요소를 반환

$("* :contains('foo')").wrap("<div class='bar'></div>"); 

아담은 제거 할 위의 코드를 작성 . 어쩌면 정규식 대체가 더 나은 해결책이 될 수 있습니다.

3

일반적으로 키워드 만 강조 표시하고 보이지 않는 텍스트 나 코드 (예 : 이미지 또는 실제 마크 업을위한 대체 텍스트 속성)가 아닌지 확인하려면 HTML 코드를 구문 분석해야합니다. If you do as Jesse Hallett suggested :

$('body').html($('body').html().replace(/(pretzel)/gi, '<b>$1</b>')); 

특정 키워드 및 문서와 관련된 문제가 발생합니다.예를 들어 :

<html> 
<head><title>A history of tables and tableware</title></head> 
<body> 
<p>The table has a fantastic history. Consider the following:</p> 
<table><tr><td>Year</td><td>Number of tables made</td></tr> 
<tr><td>1999</td><td>12</td></tr> 
<tr><td>2009</td><td>14</td></tr> 
</table> 
<img src="/images/a_grand_table.jpg" alt="A grand table from designer John Tableius"> 
</body> 
</html> 

이 상대적으로 간단한 문서는 단어 "테이블"에 대한 검색하여 찾을 수 있습니다,하지만 당신은 단지 포장 텍스트와 텍스트를 대체 할 경우이 끝낼 수 :

<<span class="highlight">table</span>><tr><td>Year</td><td>Number of <span class="highlight">table</span>s made</td></tr> 

및 이 :

<img src="/images/a_grand_<span class="highlight">table</span>.jpg" alt="A grand <span class="highlight">table</span> from designer John <span class="highlight">Table</span>ius"> 

즉, 구문 분석 된 HTML이 필요합니다. HTML 구문 분석은 까다 롭습니다. 그러나 HTML 문서 (예 : 꺽쇠 괄호가없는 열린 꺽쇠 괄호 없음)에 대한 특정 품질 제어를 가정 할 수 있다면 비 태그, 비 속성 데이터를 찾을 수있는 텍스트를 스캔 할 수 있어야합니다. 추가 마크 업.

다음은 그렇게 할 수있는 몇 가지 자바 스크립트입니다 :

function highlight(word, text) { 
    var result = ''; 

    //char currentChar; 
    var csc; // current search char 
    var wordPos = 0; 
    var textPos = 0; 
    var partialMatch = ''; // container for partial match 

    var inTag = false; 

    // iterate over the characters in the array 
    // if we find an HTML element, ignore the element and its attributes. 
    // otherwise try to match the characters to the characters in the word 
    // if we find a match append the highlight text, then the word, then the close-highlight 
    // otherwise, just append whatever we find. 

    for (textPos = 0; textPos < text.length; textPos++) { 
    csc = text.charAt(textPos); 
    if (csc == '<') { 
     inTag = true; 
     result += partialMatch; 
     partialMatch = ''; 
     wordPos = 0; 
    } 
    if (inTag) { 
     result += csc ; 
    } else { 
     var currentChar = word.charAt(wordPos); 
     if (csc == currentChar && textPos + (word.length - wordPos) <= text.length) { 
     // we are matching the current word 
     partialMatch += csc; 
     wordPos++; 
     if (wordPos == word.length) { 
      // we've matched the whole word 
      result += '<span class="highlight">'; 
      result += partialMatch; 
      result += '</span>'; 
      wordPos = 0; 
      partialMatch = ''; 
     } 
     } else if (wordPos > 0) { 
     // we thought we had a match, but we don't, so append the partial match and move on 
     result += partialMatch; 
     result += csc; 
     partialMatch = ''; 
     wordPos = 0; 
     } else { 
     result += csc; 
     } 
    } 


    if (inTag && csc == '>') { 
     inTag = false; 
    } 
    } 
    return result; 
} 
+0

이 코드에서 약간의 실수를 발견했습니다. 부분적으로 일치하지만 '<'태그를 누르면 부분 일치가 추가되기 전에 태그가 닫히고 결과에 추가됩니다 (예 : 단어를 검색하는 경우). 결과가 '

highligh

t'처럼 보이면 '(inTag) {result + = csc;} if if (inTag) {result + = partialMatch; partialMatch = ''; 결과 + = csc; } – Kevin

+0

@Kevin : 고마워, 나는이 코드를 다른 곳에서 이식했고 완전히 테스트하지는 않았다. 나는 또한 다른 하나 하나의 오류를 발견하고 그것을 고정시켰다. –

관련 문제