我使用以下代码扫描页面以查找匹配的单词并将单词转换为链接。
var linkWord = function(obj){
for(i in obj){
var x = document.body.innerHTML;
var linkStart = '<a href="'+obj[i]+'">';
var linkEnd = '</a>';
var reg = new RegExp("\\b(" + i + ")\\b(?![^<]*>|[^<>]*<\/[a])","ig");
x = x.replace(reg, " " + linkStart + i + linkEnd + " ");
document.body.innerHTML = x;
console.log(document.body.innerHTML);
}
console.log(obj);
}
linkWord({
'The':'http://www.example.com',
'Vokalia':'http://icant.co.uk',
'behind':'http://google.com',
});
这很好用但是document.body.innerHTML正在杀死页面上的其他javascript。任何人都可以提出另一种解决方案,它可以达到同样的结果,不需要document.body.innerHTML吗?
这是一个小提琴:https://jsfiddle.net/91zux4ar/
请不要图书馆。
答案 0 :(得分:2)
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);