简体   繁体   English

.insertAfter or.append 到具有 Javascript 的元素 ID。 这是一个脚本标签,所以它不能与 $

[英].insertAfter or .append to an Element Id with Javascript. it's a script tag so it can't be with $

I want to add a script after a div, this is what I have:我想在 div 之后添加一个脚本,这就是我所拥有的:

<div id="uno">insert after this</div><br />
<p>this is a paragraph</p><br />
<div>this is a div</div>

var myscript = document.createElement('script');
myscript.setAttribute('src', 'Scripts/start.debug.js');
document.body.appendChild(myscript);

and this code will ad <script src="Scripts/start.debug.js"></script> at the end of the page, and i need it after div #uno .这段代码将在页面末尾<script src="Scripts/start.debug.js"></script> ,我在 div #uno之后需要它。 What can I use instead of document.body.appendChild ?我可以用什么代替document.body.appendChild

<script>
// This function inserts newNode after referenceNode
function insertAfter( referenceNode, newNode )
{
    referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling );
}
insertAfter(document.getElementById("uno"), newScript);
</script>

Even if a nextSibling doesn't exist in the DOM it will still work "because when the second parameter of insertBefore is null then the newNode is appended to the end of the parentNode".即使 DOM 中不存在 nextSibling,它仍然可以工作,“因为当 insertBefore 的第二个参数是 null 时,newNode 将附加到 parentNode 的末尾”。 A great description can be found here: http://www.netlobo.com/javascript-insertafter.html .可以在这里找到一个很好的描述: http://www.netlobo.com/javascript-insertafter.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM