2017-04-21 53 views
1

我正在编写一个AJAX站点,为了执行我导入的脚本,我必须创建新的相同脚本才能让DOM运行它们。我想知道是否有一个简单的内置方法或其他简单的方法来将一个脚本标记的所有属性复制到另一个脚本标记,而无需单独传输它们。有没有办法将所有属性从一个元素转移到另一个元素?

基本上我所寻找的是这样的:

在HTML:

<script id = "myscript" src = "somefile.js" type = "text/javascript"></script> 

在JS:

var script = document.createElement("script"); 
script.innerHTML = document.getElementById("myscript").innerHTML; 
script.attributes = document.getElementById("myscript").attributesList; 

如何我目前得到的被分配每个单独的属性到新的脚本对象,我认为它有点乏味。

+1

没错,你可以使用[element.attributes](https://developer.mozilla.org/en-US/docs/Web/API/Element/attributes)。 –

+0

说实话,我问这个问题是懒惰的。我刚刚花了大约8个小时盯着我的电脑屏幕试图让加载的脚本运行,我只是在寻找一个简单的修复。 @Spencer,这实际上运作良好。 – Frank

回答

1

您可以使用节点#属性

var $oldScript = $("oldScript"); 
 
var $newScript = $("newScript"); 
 

 
var attributes = $oldScript.prop("attributes"); 
 

 
// loop through oldScript attributes and apply them on new script 
 
$.each(attributes, function() { 
 
    $newScript.attr(this.name, this.value); 
 
});

+1

一些技巧:1)如果您要使用Stack Snippets,请点击“Run code snippet”按钮以确保代码实际运行。 2)如果OP没有在问题或标签中提到jQuery,最好在你的答案中说出你正在使用jQuery。 –

1

我最终决定只用一个循环去填充新的脚本元素的属性列表:

for (index = old_script.attributes.length - 1; index > -1; -- index) { 

    attribute = old_script.attributes[index]; 
    new_script.setAttribute(attribute.name, attribute.value); 

} 
相关问题