.insertAfter 或 .append 到带有 Javascript 的元素 ID。这是一个脚本标签,所以它不能与 $
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6514010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
.insertAfter or .append to an Element Id with Javascript. it's a script tag so it can't be with $
提问by l3ny
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
. What can I use instead of document.body.appendChild
?
并且此代码将<script src="Scripts/start.debug.js"></script>
在页面末尾进行广告,我在 div 之后需要它#uno
。我可以用什么代替document.body.appendChild
?
回答by scrappedcola
<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". A great description can be found here: http://www.netlobo.com/javascript-insertafter.html.
即使 DOM 中不存在 nextSibling 它仍然可以工作,“因为当 insertBefore 的第二个参数为 null 时,newNode 会附加到 parentNode 的末尾”。可以在这里找到一个很好的描述:http: //www.netlobo.com/javascript-insertafter.html。