Using jQuery inside iFrame not working

2019-05-23 18:04发布

问题:

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.

回答1:

try this

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


回答2:

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.