inyfee
V2EX  ›  问与答

javascript createElement 如何插入内容 ?

  •  
  •   inyfee · Jan 30, 2013 · 3872 views
    This topic created in 4882 days ago, the information mentioned may be changed or developed.
    请看下面这个代码 :
    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> 呢?
    请大家帮帮忙。
    4 replies    1970-01-01 08:00:00 +08:00
    liaa
        1
    liaa  
       Jan 30, 2013
    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
        2
    YuHong  
       Jan 30, 2013
    createElement(); 返回的是一个Element 对象

    console.log(div.outerHTML === "<div>yeelone</div>")
    console.log(div.outerText === "yeelone")
    liaa
        3
    liaa  
       Jan 30, 2013
    @liaa 一楼的解释是错误的,别试了
    inyfee
        4
    inyfee  
    OP
       Jan 30, 2013
    @YuHong 不行呢。如果用 div.outerHTML ,会报这个错:
    selectedText.getRangeAt(0).surroundContents(div);
    Uncaught Error: NO_MODIFICATION_ALLOWED_ERR: DOM Exception 7
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3054 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 07:37 · PVG 15:37 · LAX 00:37 · JFK 03:37
    ♥ Do have faith in what you're doing.