1

我允许用户选择其中包含的文本<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>.

4

3 回答 3

3

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

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>
于 2009-11-25T16:46:27.947 回答
2

我相信问题出在这一行:

range.startContainer.textContent = result;

您实际上并没有设置 div 元素的 innerHTML,而是设置了范围容器的文本,这不会将标签解释为 HTML。相反,尝试直接从结果中设置 div 的内部 HTML 并清除范围。

为了澄清 - 此代码实际上会将所选内容转换为粗体。

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;

如果要保持选择,则需要以编程方式重置范围。

于 2009-11-25T16:52:37.260 回答
-1

在 jQuery 中,应该是$('#blob').wrap('<b></b>');. 你甚至不需要编写辅助函数。说真的,使用图书馆。不要浪费时间去研究低级的东西。

于 2009-11-25T16:49:23.010 回答