[英]How in insert dynamic JavaScript tag into iframe
最終更新:第二個代碼塊正在工作-我只是錯誤地鍵入了URL。
我正在嘗試將動態創建的腳本放入iframe。 我可以訪問iframe的頭部,但它似乎不接受附加請求。 控制台日志調用返回head標記,並且以下文本附加到主體中的效果很好。 我也嘗試將script標簽附加到正文中。 (注意: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
看到這個答案https://stackoverflow.com/a/3603496/220299
它實際上可能正在工作,但是script標簽只是不可見。
嘗試這個。
$(document).ready(function() {
$('<iframe></iframe>', {
name:"contentFrame"
,id:"contentFrame"
}).css("height", 300).css("width", 500).load(function() {
$(this).contents().find("head").append('<scr' + 'ipt type="text/javascript" src="//cross-domain.com/script.js"></scr' + 'ipt>');
}).appendTo("#content");
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.