Using jQuery inside iFrame not working

2019-05-23 18:05发布

I have a problem using jQuery inside an iFrame.

Here is my test setup:

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>

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.

2条回答
Juvenile、少年°
2楼-- · 2019-05-23 18:35

try this

$("iframe").load(function(e){
    $(this).contents().find('#B').addClass('Z');
});
查看更多
劳资没心,怎么记你
3楼-- · 2019-05-23 18:38

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

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

查看更多
登录 后发表回答