最終更新:第二個代碼塊正在工作 - 我只是錯過了鍵入的URL。如何將動態JavaScript標記插入iframe
我想將一個動態創建的腳本放入一個iframe。我可以訪問iframe的頭部,但它似乎不接受追加請求。控制檯日誌調用返回頭標記,並且以下文本追加到正文中工作正常。我也嘗試將腳本標籤附加到正文。 (注意:script標籤不在同一個域中,所以我避免使用getScript或ajax)。
$(document).ready(function() {
$('<iframe></iframe>', {
name:"contentFrame"
,id:"contentFrame"
}).css("height", 300).css("width", 500).load(function() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "//cross-domain.com/script.js";
console.log($(this).contents().find("head")); // outputs: [<head></head>]
$(this).contents().find("head").append(script); // doesn't work
$(this).contents().find("body").append(script); // doesn't work
$(this).contents().find("body").append("Test"); // works
}).appendTo("#content");
});
下面是成功追加基於下面的建議腳本的新版本,但劇本不評估(如通過簡單的警報測試)。此外,另一個奇怪的是:「工作」圖標顯示約15秒,狀態(以鉻形式顯示)「檢索...」最終停止,但沒有任何反應。
$(document).ready(function() {
$('<iframe></iframe>', {
name:"contentFrame"
,id:"contentFrame"
}).css("height", 300).css("width", 500).load(function() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "//cross-domain.com/script.js";
console.log($(this).contents().find("head"));
$(this).contents().find("head")[0].appendChild(script);
$(this).contents().find("body").append("Test");
}).appendTo("#content");
});
更新:當光標圖標終於完成工作(約10秒,這是奇怪的,因爲它是用一行代碼的本地服務器),我得到在Chrome控制檯此消息(它在所有紅色一個紅色圓圈「X」圖標旁邊):
GET http://cross-domain.com/script.js
(anonymous function)temp.html:16
jQuery.event.dispatchjquery-1.7.1.js:3261
jQuery.event.add.elemData.handle.eventHandlejquery-1.7.1.js:2880
jQuery.fn.extend.appendjquery-1.7.1.js:5771
jQuery.fn.extend.domManipjquery-1.7.1.js:5973
jQuery.fn.extend.appendjquery-1.7.1.js:5769
jQuery.each.jQuery.fn.(anonymous function)jquery-1.7.1.js:6162
(anonymous function)temp.html:18
jQuery.Callbacks.firejquery-1.7.1.js:1049
jQuery.Callbacks.self.fireWithjquery-1.7.1.js:1167
jQuery.extend.readyjquery-1.7.1.js:435
DOMContentLoaded
所以,外賣是你不能使用JQuery「追加」,但使用傳統的腳本方法將工作? – scader 2012-02-03 16:06:12