如何将文字附加到当前位置?

时间:2014-12-15 09:46:17

标签: javascript

<div>
HI!
<script>
var spanNode = document.createElement('span');
var textNode = document.createTextNode('there.');
//how to append here spanNode?
</script>
How are you?
</div>

我不想使用document.write()方法。那么,我应该在这里使用什么,所以结果将是这样的:

<div>HI!<span>there.</span>How are you?</div>

2 个答案:

答案 0 :(得分:7)

默认情况下,<script>元素会立即执行,因此在执行时,文档中只有<div>HI! <script />,&#34;你好吗&#34;部分尚未处理。在此阶段,当前处理的<script>元素将是文档中的最后一个脚本元素,因此您可以使用document.scripts[ document.scripts.length - 1 ]引用它,然后查找其父节点并附加元素。

<div>
HI!
<script>
var spanNode = document.createElement('span');
var textNode = document.createTextNode('there.');
    spanNode.appendChild( textNode );
/* this is the currently interpreted <script> element
   so you can append a child to its parent.
*/
document.scripts[ document.scripts.length - 1 ].parentNode.appendChild( spanNode );
</script>
How are you?
</div>

http://jsfiddle.net/0LsLq9x7/

编辑:为了保持全局命名空间的清洁,你可以将代码包装在一个立即执行的匿名函数中:http://jsfiddle.net/0LsLq9x7/1/

<div>
HI!
<script>
(function( scriptElement ){
    // these variables will be local to this closure
    var spanNode = document.createElement('span');
    var textNode = document.createTextNode('there.');
    spanNode.appendChild( textNode );
    scriptElement.parentNode.appendChild( spanNode );
// pass a reference to the script element as an argument to the function
}(document.scripts[ document.scripts.length - 1 ]));
</script>
How are you?
</div>

答案 1 :(得分:0)

您可以先获取当前脚本。然后在脚本之前(或之后)添加元素..

&#13;
&#13;
<div>
HI!
<script id="myscript">
var spanNode = document.createElement('span');
var textNode = document.createTextNode('there.');
    spanNode.appendChild( textNode );
  
    //appending the span node
    var ele = document.currentScript;   //get current script element
    ele.parentNode.insertBefore(spanNode,ele);  //append the span before the script
</script>
How are you?
</div>
&#13;
&#13;
&#13;