将HTML块写为字符串



我想在用户输入textarea(使用JavaScript)时显示HTML。这样:

Every thing fine <a href="/toto"> link </a>

如果不使用" pre"标签,我该怎么做?我只想避免HTML解释。

谢谢

只需创建一个文本节点…

var node = document.createTextNode(a_string);

…并将其添加到某个地方的文档中……

document.body.appendChild(node);

,所以您有一个字符串:

str='Every thing fine <a href="/toto"> link </a>';

您更换括号:

str.replace('<', '&lt;').replace('>', '&gt;');

然后写入文档:

document.write(str);

或设置现有元素内容:

elem.innerHTML = str;

您可以设置textContent。

elem.textContent = "<div>foo</div>";

但是,对于浏览器的兼容性,您应该在代码开头进行类似的操作:

var textContent = ('textContent' in document) ? 'textContent' : 'innerText';

然后这样使用:

elem[textContent] = "<div>foo</div>";

jquery.html()将为您做到这一点

最新更新