javascript 在 iFrame 中使用 jQuery 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18536947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 12:19:28  来源:igfitidea点击:

Using jQuery inside iFrame not working

javascriptjqueryhtmliframe

提问by user63457

I have a problem using jQuery inside an iFrame.

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

Here is my test setup:

这是我的测试设置:

index.html:

索引.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:

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

Normally when the page is loaded, in the source, "Z" should be added as a class, but it doesn't. Does anyone have an idea what the problem might be? Both files are in the same (local) folder.

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

回答by

try this

试试这个

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

回答by Joseph Silber

You have to run it from a webserver with the HTTP scheme (http://or https://).

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

Using the file scheme (file://) prevents this sort of cross frame access in some browsers.

使用文件方案 ( file://) 可防止在某些浏览器中进行此类跨框架访问。