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

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

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

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

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


当前回答

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

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

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

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

其他回答

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

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

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

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

可以使用jQuery的.contents()方法。

如果iframe与主页位于同一域,则.contents()方法也可用于获取iframe的内容文档。

$(document).ready(function(){
    $('#frameID').load(function(){
        $('#frameID').contents().find('body').html('Hey, i`ve changed content of <body>! Yay!!!');
    });
});

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

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

参考

如果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编辑外部页面而不拒绝访问等的示例。。。

我觉得这样更干净:

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