[英]Changing Text (outside of HTML-Tags) to links
我想要一個JavaScript,可以在頁面上搜索正則表達式(說“ abcabc”),然后用鏈接替換該正則表達式。
我現在的嘗試是:
function replText(text) {
var exp = new RegExp("(abcabc)", "g");
return text.replace(exp, "<a href=\"http://my_site.com/$1\">$1</a>");
}
// http://stackoverflow.com/questions/5494259/jquery-change-all-elements-text
// Thanks to Box9!
function recursiveReplace(node) {
if (node.nodeType == 3) { // text node
node.nodeValue = replText(node.nodeValue);
} else if (node.nodeType == 1) { // element
$(node).contents().each(function () {
recursiveReplace(this);
});
}
}
recursiveReplace(document.body);
哪一種工作。 但是再說一次,不是真的,因為它不會創建鏈接,而是創建<a href =“ -like字符串(帶有轉義的HTML實體)。
我可以使用Jquery,但我不是該專家。 誰能知道該怎么做? 我不想將其替換為HTML標記(例如'class =“ abcabc”'等)。
提前致謝!
嘗試
var exp = new RegExp("(abcabc)", "g");
function replText(text) {
return text.replace(exp, "<a href=\"http://my_site.com/$1\">$1</a>");
}
// http://stackoverflow.com/questions/5494259/jquery-change-all-elements-text
// Thanks to Box9!
function recursiveReplace(node) {
if (node.nodeType == 3) { // text node
$(node).replaceWith(replText(node.nodeValue))
} else if (node.nodeType == 1) { // element
$(node).contents().each(function () {
recursiveReplace(this);
});
}
}
recursiveReplace(document.body);
演示: 小提琴
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.