2017-04-21 75 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); 

} 
相關問題