javascript createElement 如何插入内容 ?

2013-01-30 11:56:46 +08:00
 yeelone
请看下面这个代码 :
http://jsfiddle.net/yeelone/UuuMj/

主要代码:
// 所选内容替换成指定内容
function replaceText(text) {
var selectedText = window.getSelection();
var div = document.createElement('div');
var t = document.createTextNode(text);
div.appendChild(t);
console.log(t);
console.log(div);
selectedText.getRangeAt(0).surroundContents(div);
selectedText.removeAllRanges();
}

输出的情况是:
"yeelone"
<div></div>

为什么不是:
"yeelone"
<div>yeelone</div> 呢?
请大家帮帮忙。
3359 次点击
所在节点    问与答
4 条回复
liaa
2013-01-30 12:16:58 +08:00
lz 将你上面的这3行改一下就行
--var div = document.createElement('div');
var anotherDiv = document.createElement('div');

--div.appendChild(t);
antherDiv.appendChild(t);

--console.log(div);
console.log(anotherDiv);

你下面那个console.log输出的div其实是指向到了你html那个空div中去了
YuHong
2013-01-30 12:17:05 +08:00
createElement(); 返回的是一个Element 对象

console.log(div.outerHTML === "<div>yeelone</div>")
console.log(div.outerText === "yeelone")
liaa
2013-01-30 12:25:09 +08:00
@liaa 一楼的解释是错误的,别试了
yeelone
2013-01-30 13:35:39 +08:00
@YuHong 不行呢。如果用 div.outerHTML ,会报这个错:
selectedText.getRangeAt(0).surroundContents(div);
Uncaught Error: NO_MODIFICATION_ALLOWED_ERR: DOM Exception 7

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/59248

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX