简体   繁体   English

HTML javascript函数创建元素

[英]HTML javascript function to create element

I have this function inside a javascript: 我在javascript中具有以下功能:

function inc(filename) {
        var head = document.getElementsByTagName('head').item(0);
        script = document.createElement('script');
        script.src = filename;
        script.type = 'text/javascript';
        head.appendChild(script);
    }

If I call this function, it will create one element in the DOM. 如果我调用此函数,它将在DOM中创建一个元素。 That's fine. 没关系。
But if I call it another time, I want it to create an element on top of the previous element so that I only have one element created by this funtion in the DOM. 但是,如果我再次调用它,我希望它在前一个元素之上创建一个元素,这样我在DOM中只有一个通过此功能创建的元素。
Is it already doing that? 已经这样做了吗? If not, how can I make it happen? 如果没有,我该如何实现?

I don't understand the DOM very well as you can see by this question. 从这个问题可以看出,我对DOM不太了解。

Use replaceChild() When you review the Snippet, you'll have to use the dev tools to see that it worked. 使用replaceChild()在查看代码段时,您必须使用开发工具才能查看其功能。

SNIPPET SNIPPET

 function swap(parent, replacement, url) { var alpha = document.querySelector(parent); var target = alpha.childNodes[0]; var omega = document.createElement(replacement); omega.src = url; alpha.replaceChild(omega, target); } swap('head', 'script', 'http://end.com'); 
 <!doctype html> <html> <head> <script src="http://beginning.com"></script> </head> <body> </body> </html> 

While this is completely pointless, you could easily achieve that behavior by changing this line 尽管这毫无意义,但您可以通过更改此行轻松实现该行为

script = document.createElement('script');

to

script = script || document.createElement('script');

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

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