javascript - 如何强制浏览器呈现标签而不是在更改后的 div :innerHTML? 上向用户显示标签

标签 javascript html render innerhtml

我允许用户选择 <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 显示标签已转义 &lt;b&gt;而不是 <b> .

最佳答案

这不是导致您的问题的原因,但是.. 这不是错了吗?

var txt = el.innerHTML;
el.innerHTML = txt;

编辑:

试试这个:

<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>

<input type="button" value="sample" onclick='tagText();'>

and...

<script>
  function tagText() {
    var range = window.getSelection().getRangeAt(0);
    range.surroundContents(document.createElement("b"));
  }
</script>

关于javascript - 如何强制浏览器呈现标签而不是在更改后的 div :innerHTML? 上向用户显示标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1798177/

相关文章:

html - HTML 呈现的 MVC3 TextArea 问题

javascript - JavaScript 中的确认()

javascript - JS,jQuery 冲突..帮助?

javascript - 将原始 CSS 转换为 Javascript DOM 样式属性

javascript - 当它悬停在页面右侧时,将工具提示跨度重新对齐到左侧

jquery - 谷歌地图嵌入与粘性导航栏重叠

javascript - If/Else jQuery 跳过未定义的值

javascript - 将 Canvas 元素放在前面?

templates - 从json添加到数组并在模板中执行数据

r - 在查看器 Pane 中打开 R Markdown