[英]Why does wrapping tags around text with Javascript RegEx display the tags as text?
I'm attempting to wrap tags around certain words in a set of links, but the tags are rendering as text. 我正在尝试将标签围绕一组链接中的某些单词进行包装,但是标签呈现为文本。 Why is this, and what can I do to get them to render as HTML? 为什么会这样,如何使它们呈现为HTML?
I have the following Javascript: 我有以下Javascript:
$('h3 a').each( function(){
var text = this.firstChild.nodeValue;
this.firstChild.nodeValue = text.replace(
/(^Men\'s|Men’s|Women\'s|Women’s)/g,
'<span class=\"title\">$1</span>'
);
});
and here is a sample of the HTML: 这是HTML的示例:
<p><a href="products1.html">Women's Apparel</a></p>
<p><a href="products2.html">Men's Apparel</a></p>
My in-browser result is something like: 我在浏览器中的结果是这样的:
<span class="title">Women's</span> Apparel
<span class="title">Men's</span> Apparel
...but obviously I want those spans to be functional elements rather than displaying as text in the browser. ...但是显然我希望这些范围是功能性元素,而不是在浏览器中显示为文本。
What am I doing wrong? 我究竟做错了什么?
You have to either create the DOM nodes yourself, which is tedious, or work with innerHTML
, which will get parsed and turned into a DOM subtree for you: 您必须自己创建乏味的DOM节点,或者使用innerHTML
,它将被解析并转换为DOM子树:
$('h3 a').each( function(){
var text = this.firstChild.nodeValue;
this.innerHTML = text.replace(
/(^Men\'s|Men’s|Women\'s|Women’s)/g,
'<span class=\"title\">$1</span>'
);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.