我允许用户选择其中包含的文本<div></div>
并将其更改为粗体文本。换句话说,从<div>this is some text</div>
到<div>this is <b>some</b> text</div>
。一切正常,除了当我将 div.innerHTML 更改为 时this is <b>some</b> text
,<b>some</b>
标签会显示给用户,而不是呈现为 HTML 并显示一些粗体。这一切都发生在 Javascript 的客户端。
如何强制浏览器呈现标签而不是向用户显示它们?
根据请求,这是代码...
HTML...
<div id="blob">
One simple, but not very efficient implementation of a dictionary is a linked
list. In this implementation all operations take linear time in the worst case
(and even in the average case), assuming that insertions first check whether the
item is in the current list. A more scalable implementation of a dictionary is a
balanced search tree. In this lecture note we present two even more efficient data
structures based on hashing.
</div>
Javascript...
tagText(document.getElementById("blob"),"<b>","</b>");
和...
//======================================================================
function tagText(el,tagstart,tagend)
{
var range = window.getSelection().getRangeAt(0);
var rtxt = range.startContainer.textContent;
var rlen = rtxt.length;
var start = range.startOffset;
var stop = range.endOffset;
var result = rtxt.substring(0,start) + tagstart + rtxt.substring(start,stop) + tagend + rtxt.substring(stop,rlen);
// el.innerHTML = result;
range.startContainer.textContent = result;
var txt = el.innerHTML;
el.innerHTML = txt;
}
//======================================================================
通过 firebug 查看 div:innerHTML 显示标签被转义<b>
而不是<b>
.