Javascript 将文本转换为包含 html 标记的超链接



我创建了一个简单的JavaScript函数,它可以接受一个字符串并用超链接替换它。 我的问题是如何转换包含 html 标签的字符串。 我无法弄清楚这部分。 任何帮助,不胜感激。

function createlink( text) {

var replacetxt = "<a id="'Temp5'" onClick=" testfunction()" href="#" style="color: black;background-color: green;text-decoration: none">" +  text + "</a>";
var re = new RegExp(text,'g');
document.body.innerHTML = document.body.innerHTML.replace(re, replacetxt);
}
//This Works
//createlink("My first paragraph");
//This does not work
createlink("My first paragraph~2");
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph<sup>~2</sup></p>
</body>
</html>

您可以在执行 HTML 字符串匹配时将标签添加到输入中。

function createlink( text) {
var replacetxt = "<a id="'Temp5'" onClick=" testfunction()" href="#" style="color: black;background-color: green;text-decoration: none">" +  text + "</a>";
var re = new RegExp(text,'g');
document.body.innerHTML = document.body.innerHTML.replace(re, replacetxt);
}
function testfunction(){
alert('testfunction called')
}
//This Works
//createlink("My first paragraph");
//This does not work
createlink("My first paragraph<sup>~2</sup>");
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph<sup>~2</sup></p>
</body>
</html>

您可能想阅读此链接 - https://medium.com/better-programming/whats-best-innertext-vs-innerhtml-vs-textcontent-903ebc43a3fc

function createlink(text) {
var replacetxt = "<a id="'Temp5'" onClick=" testfunction()" href="#" style="color: black;background-color: green;text-decoration: none">" + text + "</a>";
var re = new RegExp(text, 'g');
var el = document.getElementById('t');

el.innerHTML = el.innerText.replace(re, replacetxt);
}
function testfunction(){
alert('Random test function is called for testing')
}
//This Works
//createlink("My first paragraph");
//This does not work
createlink("My first paragraph~2");
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p id='t'>My first paragraph<sup>~2</sup></p>
</body>
</html>

最新更新