我在iframe中有一个脚本,该脚本使用jquery查找元素,但是当它运行时,它只会在iframe之外找到一个元素-而不是在iframe里面的元素。
请帮助我隔离仅在iframe中执行的脚本。
我这里有一个例子:我的例子
如我的链接示例所示,如何创建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
我明白了:一个可行的解决方案
//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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句