如何将文字附加到当前位置? [英] How to append text to current position?
问题描述
<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()方法。那么,我应该在这里使用什么,所以结果是这样的:
I don't want to use document.write() method. So, what should I use here so the result would be like this:
<div>HI!<span>there.</span>How are you?</div>
推荐答案
A < script>默认情况下
元素立即执行,因此在执行时只有< div> HI! < script />
在文档中,你好吗部分尚未处理。在这个元素中,当前处理的< script>
元素将是文档中的最后一个脚本元素,因此您可以使用 document.scripts [ document.scripts.length - 1]
,然后找到它的父节点并附加元素。
A <script>
element by default is executed immediately, so at the moment of execution there's just <div>HI! <script />
in the document, the "How are you" part hasn't been processed yet. At this moement the currently processed <script>
element will be the last of script elements in your document so you can reference it using document.scripts[ document.scripts.length - 1 ]
, then find its parent node and append the elements.
<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/1/
to keep the global namespace clean you could wrap the code in an anonymous function which executes immediately: 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>
这篇关于如何将文字附加到当前位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!