我有一个页面https://dev.leadformly.com/datepicker有一个iframe 在那个特定的''中,我通过以下代码通过ajax调用动态编写HTML代码。
<script>
$(document).ready(function(){
$.post(URL,
function (data) { //here it retruns the HTML code
$("body").html('<iframe style="width:100%;height:384px;"></iframe>');
$("body iframe")[0].contentDocument.write(data.democode);
},
'json'
);
});
</script>
现在当我点击日期选择器时,它会在控制台中抛出错误,如:
Uncaught TypeError: Cannot read property 'top' of undefined
你能帮我解决这个问题吗?或者只是解释原因,这将有助于我解决它
答案 0 :(得分:12)
您收到此错误是因为您尝试从包含它的父DOM
访问iFrame
的内部DOM
。来自父DOM
的“点击”事件无法调用子iFrame
内的元素。
请问您为什么要在这种情况下使用iFrame
?我几乎可以向你保证,最好不要使用它。
答案 1 :(得分:3)
我认为jQuery无法读取iframe元素,这就是它显示的原因 无法读取未定义错误的属性顶部。
在iframe元素中使用id="ifreame"
然后它应该可以正常工作。
<iframe id="ifreame" style="width:100%;height:384px;"></iframe>
的jQuery
$("body #iframe")[0].contentDocument.write(data.democode);
答案 2 :(得分:3)
您拥有的最后一个选项是尝试使用沙盒属性。
allow-scripts: Allows the embedded browsing context to run scripts (but not create pop-up windows). If this keyword is not used, this operation is not allowed.
https://developer.mozilla.org/en/docs/Web/HTML/Element/iframe
如果这不起作用,请远离iframe。 iframe元素被创建为沙盒环境,并且在打开allow-scripts时容易出现非常高的安全风险。生成的iframe中的网页/外部网站可以执行任何操作......如果您删除沙盒,则可以访问凭据,Cookie,访问等。
如果您想在其内容中访问DOM,则不建议使用Iframe。如果您唯一需要完全或部分隔离,请尝试使用Web组件的隔离方法: