我想使用jQuery在iframe中操纵HTML。

我想我可以通过将jQuery函数的上下文设置为iframe的文档来实现这一点,比如:

$(function(){ //document ready
    $('some selector', frames['nameOfMyIframe'].document).doStuff()
});

然而,这似乎不起作用。一点检查显示,帧['nameOfMyIframe']中的变量未定义,除非等待一段时间加载iframe。然而,当iframe加载时,变量是不可访问的(我得到了拒绝权限的类型错误)。

有人知道这方面的工作吗?


当前回答

Use

iframe.contentWindow.document

而不是

iframe.contentDocument

其他回答

我更喜欢使用其他变体进行访问。从父级可以访问子级iframe中的变量。$也是一个变量,您可以访问它的调用window.iframe_id$

例如,window.view.$('div').hide()-隐藏iframe中id为'view'的所有div

但是,它在FF中不起作用。为了更好的兼容性,您应该使用

$('#iframe_id')[0].contentWindow$

如果<iframe>来自同一个域,则元素很容易作为

$("#iFrame").contents().find("#someDiv").removeClass("hidden");

参考

我觉得这样更干净:

var $iframe = $("#iframeID").contents();
$iframe.find('selector');

如果iframesrc来自另一个域,您仍然可以这样做。您需要将外部页面读入PHP并从您的域中回显。这样地:

iframe_page.php

<?php
    $URL = "http://external.com";

    $domain = file_get_contents($URL);

    echo $domain;
?>

然后是这样的:

显示页面.html

<html>
<head>
  <title>Test</title>
 </head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>

<script>

$(document).ready(function(){   
    cleanit = setInterval ( "cleaning()", 500 );
});

function cleaning(){
    if($('#frametest').contents().find('.selector').html() == "somthing"){
        clearInterval(cleanit);
        $('#selector').contents().find('.Link').html('ideate tech');
    }
}

</script>

<body>
<iframe name="frametest" id="frametest" src="http://yourdomain.com/iframe_page.php" ></iframe>
</body>
</html>

以上是如何通过iframe编辑外部页面而不拒绝访问等的示例。。。

如果下面的代码不起作用

$("#iFrame").contents().find("#someDiv").removeClass("hidden");

以下是使其工作的可靠方法:

$(document).ready(function(){ 
  setTimeout(
    function () {
      $("#iFrame").contents().find("#someDiv").removeClass("hidden");
    },
    300
  );
});

这样,脚本将在300毫秒后运行,因此它将有足够的时间加载iFrame,然后代码将生效。有时iFrame不会加载,脚本会在它之前执行。300ms可以根据您的需要调整为任何其他值。