https://jsfiddle.net/91zux4ar/10/
這是一個很大的研究和工作..但它是值得的結果。我想我會發布的jQuery插件
function wordToLinks(words) {
function getAllTextNodes(ele) {
var blackListedElements = ["a", "address", "area", "audio", "base", "br", "button", "canvas", "code", "data", "datalist", "embed", "fieldset", "form", "head", "hr", "html", "iframe", "img", "input", "ins", "keygen", "label", "link", "map", "math", "menu", "menuitem", "meta", "meter", "nav", "noscript", "object", "optgroup", "option", "output", "param", "pre", "progress", "rtc", "ruby", "samp", "script", "select", "source", "style", "svg", "textarea", "time", "title", "track", "var", "video", "wbr", "applet", "basefont", "dir", "font", "isindex", "noframes"];
var nodes = [];
(function recrusive(element) {
var all_nodes = element.childNodes,
l = all_nodes.length,
child;
for (var i = 0; i < l; i++) {
child = all_nodes[i];
if (child.nodeType == 3) {
nodes.push(child);
} else if (child.nodeType == 1 && blackListedElements.indexOf((child.tagName).toLowerCase()) < 0) {
recrusive(child);
}
}
})(ele);
return nodes.filter(function (e) {
return (/\w/).test(e.textContent);
});
}
function createAtag(str, url) {
var tag = document.createElement('a');
tag.innerText = str;
tag.href = url;
tag.style.display = 'inline';
return tag;
}
function getIndex(node, word) {
//return node.nodeValue.toLowerCase().indexOf(word.toLowerCase());
var reg = RegExp("\\b(" + word + ")\\b(?![^<]*>|[^<>]*<\/[a])","ig");
var result = reg.exec(node.nodeValue);
var index = (result != undefined) ? result.index : -1;
return index;
}
var all_nodes = getAllTextNodes(document.body);
var w = Object.keys(words);
all_nodes.forEach(function (node) {
w.forEach(function (word) {
var c_node = node,
reg = new RegExp(word, 'i'),
tag, i;
i = getIndex(c_node, word);
while (i > -1) {
var second = c_node.splitText(i);
c_node = second.splitText(word.length);
tag = createAtag(second.nodeValue, words[word])
second.parentElement.replaceChild(tag, second);
i = getIndex(c_node, word);
}
});
});
}
var words = {
'the': 'http://www.example.com',
'Vokalia': 'http://icant.co.uk',
'behind': 'http://google.com',
};
wordToLinks(words);
的可能的複製[如何動態地添加錨標記在JavaScript中一個div?](http://stackoverflow.com/questions/5519747/how-to- add-anchor-tags-dynamic-to-a-div-in-javascript) –
不是重複的,那個問題的答案要求你知道要工作的元素類型或id。我的示例查找頁面中的所有匹配詞並創建鏈接。 – afro360
您可以將鏈接附加到正文。 –