我有一个用 ahref 标签替换电话号码的 Chrome 扩展程序。在这个 ahref 标记中,我想调用一个 javascript 函数。为简化起见,我使用“javascript:alert('hey')”作为 href 值。当我执行下面的命令时,我得到警报功能的“regs is not defined”,但对于 console.log,它显示正确的值。我试图附加到现有问题,因为它是相关的,但有人删除了它并要求我发布一个新问题。
var re = /(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]??)\s*)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)([2-9]1[02-9]??|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})/
var regs;
var walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, function(node) {
if((regs = re.exec(node.textContent))) {
// make sure the text nodes parent doesnt have an attribute we add to know its all ready been highlighted
if(!node.parentNode.classList.contains('highlighted_text')) {
var match = document.createElement('A');
match.appendChild(document.createTextNode(regs[0]));
console.log(regs[0]);
match.href = "javascript:alert(regs[0])";
console.log(node.nodeValue);
// add an attribute so we know this element is one we added
// Im using a class so you can target it with css easily
match.classList.add('highlighted_text');
var after = node.splitText(regs.index);
after.nodeValue = after.nodeValue.substring(regs[0].length);
node.parentNode.insertBefore(match, after);
}
}
return NodeFilter.FILTER_SKIP;
}, false);
// Make the walker step through the nodes
walker.nextNode();