【问题标题】:Using jQuery inside iFrame not working在 iFrame 中使用 jQuery 不起作用
【发布时间】:2013-08-30 15:50:03
【问题描述】:

我在 iFrame 中使用 jQuery 时遇到问题。

这是我的测试设置:

index.html:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function(){
    $("#A").contents().find('#B').addClass('Z');    
});

</script>
</head>
<body>

<iframe id="A" src="test.html" style="width:700px; height: 1000px;" frameborder="0"></iframe>

</body>
</html>

test.html:

<html>
<head>
<title>test</title>
</head>
<body>
<div id="B">testcontent</div>
</body>
</html>

通常当页面加载时,在源代码中,“Z”应该作为一个类添加,但它没有。有谁知道问题可能是什么?这两个文件都在同一个(本地)文件夹中。

【问题讨论】:

  • 可能是函数在 iframe 内容加载之前执行。尝试这样做: $('iframe').ready(function() { });而是看看它是否有效
  • .ready 在 iframe 上没有任何用处。 .load 另一方面可能会有所帮助。

标签: javascript jquery html iframe


【解决方案1】:

试试这个

$("iframe").load(function(e){
    $(this).contents().find('#B').addClass('Z');
});

【讨论】:

    【解决方案2】:

    您必须使用 HTTP 方案(http://https://)从网络服务器运行它。

    在某些浏览器中使用文件方案 (file://) 可以防止这种跨框架访问。

    【讨论】:

      猜你喜欢
      • 2011-03-07
      • 1970-01-01
      • 2013-06-27
      • 1970-01-01
      • 1970-01-01
      • 2011-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多