2012-04-23 3 views
2

지정된 "#content"div에서 특정 키워드를 검색하는 위젯을 작성하고 있습니다. var content = $('content').html(); div의 전체 내용을 대체하지 않고 자바 스크립트를 사용하여 텍스트에 링크 삽입

  • <a href='link.html'>keyword</a>
  • 에 특정 키워드를 대체하는 어떤 정규 표현식에를 사용

    • 는 내용의 HTML에 변수를 동일하게 설정 : 여기

      내가 원래 jQuery를 (간체 버전)를 사용하여 설정하는 방법입니다

    • 새로운 컨텐츠와 컨텐츠 사업부의 HTML 대체 : 이것은 대부분의 작동 $('content').html(content);

    을하지만, 문제는 "#content"div에 자바 스크립트가 포함되어있을 때 발생합니다. $('content').html(content)을 설정하면 $('content') div에 포함 된 모든 자바 스크립트 코드가 다시 실행되므로 오류가 발생할 수 있습니다. 이 사이트는 어떤 사이트에서든 작업 할 수있는 위젯이므로 콘텐트 div에 대한 제어권이없고 자바 스크립트가 있는지 여부도 다릅니다.

    내 질문에, <a href='link.html'>keyword</a>이라는 키워드 만 바꾸고 div의 전체 내용을 바꾸지 않으시겠습니까?

    답변

    4

    내 질문에, 해당 div의 전체 내용을 바꾸지 않고 <a href='link.html'>keyword</a> 키워드 만 바꾸는 방법이 있습니까?

    예. jQuery가 실제로 당신에게별로 도움이되지 않는 몇 안되는 장소 중 하나입니다.

    원시 DOM API 수준에서는 요소의 실제 텍스트가 포함 된 Text node의 코드가 splitText function이며이 코드를 사용하여 노드를 특정 위치의 두 인접 노드로 나눌 수 있습니다. 따라서 귀하의 경우 단어의 시작 부분에서 분할 한 다음 끝 부분에서 다시 분할 한 다음 중간 부분을 Text 노드로 새 앵커에 배치하십시오.

    다음은 예입니다. Live copy | source

    HTML :

    <input type="button" id="theButton" value="Make it a link"> 
    <p id="example">This is the example paragraph.</p> 
    

    자바 스크립트 :

    jQuery(function($) { 
    
        $("#theButton").click(function() { 
        var targetWord, p, textNode, index, nodeWord, nodeAfter; 
    
        // Our target word 
        targetWord = "example"; 
    
        // Get the paragraph using jQuery; note that after we 
        // use jQuery to get it (because it fixes getElementById for 
        // us on older versions of IE), we then use [0] to access 
        // the *raw* `p` element. 
        // Then get the text node from it. 
        p = $("#example")[0]; 
        textNode = p.firstChild; 
    
        // Find our text in the text node 
        index = textNode.nodeValue.indexOf(targetWord); 
        if (index !== -1) { 
         // Split at the beginning of the text 
         nodeWord = textNode.splitText(index); 
    
         // Split the new node again at the end of the word 
         nodeAfter = nodeWord.splitText(targetWord.length); 
    
         // Insert a new anchor in front of the word 
         anchor = document.createElement('a'); 
         anchor.href = "http://stackoverflow.com"; 
         p.insertBefore(anchor, nodeWord); 
    
         // Now move the word *into* the anchor 
         anchor.appendChild(nodeWord); 
        } 
        }); 
    
    }); 
    

    당연히 당신이 향상하고 싶은 것 몇 가지가 있습니다 :

    • 는 작성하지 않고 index === 0 경우 핸들은 부모 요소의 시작 부분에 빈 텍스트 노드. (무해하지만 이상적이지 않음)
    • 단어가 부모의 에있는 경우를 처리하십시오. 따라서 빈 텍스트 노드로 끝나지 않게됩니다. (다시.)
    +0

    감사합니다, T.J. 이것은 내가 찾고 있었던 바로 그 것이다! – carboneau

    +0

    @carboneau : 좋은 거래, 도움이 된 것을 기쁘게 생각합니다. –

    0

    예.하지만 모든 텍스트 노드를 수동으로 반복해야합니다.

    일단 태그가 실행되면 페이지에 필요하지 않으므로 (모든 것이 메모리에 유지되므로) 먼저 <script> 태그를 제거하는 것이 더 쉽습니다. #content 요소에서 스크립트를 제거합니다

    $('#content script').remove(); 
    

    는, 당신은 당신이 문제없이 코드를 대체 기존 실행할 수 있습니다. 이 같은 모든 컨텐츠를 교체하지 않고 키워드 만 교체 할 수 있습니다

    1

    ,

    function keywordconvert(str, p1, offset, s) { 
         return "<a href=\"link?t="+encodeURIComponent(p1)+"\">"+p1+"</a>"; 
    } 
    
    function search(keyword) { 
        var content = document.getElementById("content"); 
        var re = new RegExp("("+keyword+")","g"); 
        content.innerHTML = content.innerHTML.replace(re, keywordconvert); 
    } 
    

    USAGE

    search("keyword"); 
    

    DEMO

    관련 문제