我正在创建一个Web扩展程序,需要动态将内部文本更改为链接。由于它是一个Web扩展程序,因此我无法对此文本的位置做出太多假设。此外,更改需要动态加载(这是我遇到的主要问题)。

例如,我需要在页面上找到文本“ foo”的所有实例,并将其替换为<a href="www.mylink.com">foo</a>,以便现在页面上的文本显示为链接。我具有以下功能,可以正确替换出现的位置,但是它插入的<a>标签只是在浏览器中显示为原始html,而不是显示为链接。



function replace_with_link()
{
  var link = "https://google.com";
  var name = "Lorem Ipsum";
	var link_wrapper = "<a href=\"" + link + "\">" + name + "</a>";
	replaceText('*', name, link_wrapper, 'g');
}

function replaceText(selector, text, newText, flags)
{
	var matcher = new RegExp(text, flags);
	$(selector).each(function ()
	{
		var $this = $(this);
		var replaced_text = "";
		if (!$this.children().length)
		{
		   $this.text($this.text().replace(matcher, newText));
		}
	});
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>
<button onclick="replace_with_link();">Click me</button>

</body>
</html>

最佳答案

TLDR:将$this.text(...)更改为$this.html(...)

较长的答案是两种方法之间的主要区别:


html方法将“设置匹配元素集中每个元素的HTML内容”。
text方法还将设置元素的内容,但是“根据需要转义提供的字符串,以便可以正确地用HTML呈现”。


最后一点很关键,因为“为此,它调用DOM方法.createTextNode(),不会将字符串解释为HTML”。基本上,这意味着任何HTML都将被转义,以便能够显示为文本。

function replace_with_link() {
  var link = "https://google.com";
  var name = "Lorem Ipsum";
  var link_wrapper = "<a href=\"" + link + "\">" + name + "</a>";
  replaceText('*', name, link_wrapper, 'g');
}

function replaceText(selector, text, newText, flags) {
  var matcher = new RegExp(text, flags);
  $(selector).each(function() {
    var $this = $(this);
    var replaced_text = "";
    if (!$this.children().length) {
      $this.html($this.text().replace(matcher, newText));
    }
  });
}

10-07 19:59
查看更多