我在iframe中有一个脚本,它使用jquery查找元素,但是当它运行时,它只会在iframe之外找到一个元素 - 而不是iframe中的元素。
请帮助我将脚本隔离到iframe内部。
我在这里有一个例子:my example
如何创建我在链接示例中显示的iframe:
//Head to iframe:
var head = '<meta charset="utf-8">' +
'<meta http-equiv="X-UA-Compatible" content="IE=edge">' +
'<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">' +
'<script src="http://code.jquery.com/jquery-1.10.2.js"><\/script>';
//Body to iframe that contains a script that I would like only to run inside the iframe:
var body = '<code id="codeInside">code tag inside</code>' +
'<script>var codeTag = $("code").text("TAG FOUND!!");<\/script>';
//Insert the iframe:
var iframe = $('<iframe src="javascript:\'\'">').appendTo($('body'));
iframe.contents().find('head').html(head); //Append head til the iframe
iframe.contents().find('body').html(body); //Append body to the iframe
答案 0 :(得分:0)
你有没有尝试过正常的做法
var codeTag = iframe.contents().find("code").text("TAG FOUND!!"); console.log("codeTag", codeTag);
答案 1 :(得分:0)
我明白了:a working solution
//Head to iframe:
var head = '<head><meta charset="utf-8">' +
'<meta http-equiv="X-UA-Compatible" content="IE=edge">' +
'<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">' +
'<script src="http://code.jquery.com/jquery-1.10.2.js"><\/script></head>';
//Body to iframe that contains a script that I would like only to run inside the iframe:
var body = '<body><code id="codeInside">code tag inside</code>' +
'<script>var codeTag = $("code").text("TAG FOUND!!"); console.log("codeTag", codeTag);<\/script></body>';
//Insert the iframe:
var iframe = $('<iframe src="javascript:\'\'">').appendTo($('body'));
var doc = iframe[0].contentWindow.document;
doc.open();
doc.write(head);
doc.write(body);
doc.close();