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

2024-01-14

<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>

A <script>默认情况下,元素会立即执行,因此在执行时只有<div>HI! <script />在文档中,“你好吗”部分尚未处理。此时当前正在处理的<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/

编辑:为了保持全局命名空间干净,您可以将代码包装在立即执行的匿名函数中:http://jsfiddle.net/0LsLq9x7/1/ 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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将文本附加到当前位置? 的相关文章

随机推荐