在iFrame中使用jQuery不起作用

Using jQuery inside iFrame not working

本文关键字:jQuery 不起作用 iFrame      更新时间:2023-09-26

我在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").load(function(e){
    $(this).contents().find('#B').addClass('Z');
});

您必须在具有HTTP方案(http://https://)的Web服务器上运行它。

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