내 질문에, 해당 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
경우 핸들은 부모 요소의 시작 부분에 빈 텍스트 노드. (무해하지만 이상적이지 않음)
- 단어가 부모의 끝에있는 경우를 처리하십시오. 따라서 빈 텍스트 노드로 끝나지 않게됩니다. (다시.)
감사합니다, T.J. 이것은 내가 찾고 있었던 바로 그 것이다! – carboneau
@carboneau : 좋은 거래, 도움이 된 것을 기쁘게 생각합니다. –