使用jquery从父页面访问子IFrame中的元素 [英] Accessing element in child IFrame from parent page using jquery

查看:128
本文介绍了使用jquery从父页面访问子IFrame中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用以下代码从父文档访问iframe中文档的元素,但由于某些原因无法使其工作。



Parent.html:

 <!DOCTYPE html> 
< html>
< head>
< title>父< / title>
< script src ='http://code.jquery.com/jquery-latest.min.js'>
< / script>
< / head>
< body>
< iframe id =iframe1src =iframe.html>
< / iframe>
< script type ='text / javascript'>

'('#iframe1')。ready(function()
{
console.log($('#iframe1')。contents()。find(# testDiv)。html());
});
< / script>
< / body>
< / html>

IFrame.html:

 <!DOCTYPE html> 
< html>
< head>
< title> Iframe< / title>
< / head>
< body>
< div id =testDiv>
工程!
< / div>
< / body>
< / html>

所有我在控制台日志中都是'undefined'而不是'Works!'。我在做什么错了?



在此先感谢。


$ b

  $('#iframe1')。load(function(){
console .log($('#iframe1')。contents()。find(#testDiv)。html());
});


I am trying to access the elements of the document in the iframe from the parent document using the following code, but cannot get it to work for some reason.

Parent.html :

<!DOCTYPE html>
<html>
    <head>
        <title>Parent</title>
        <script src='http://code.jquery.com/jquery-latest.min.js'> 
        </script>
    </head>
    <body>
        <iframe  id="iframe1" src="iframe.html">
        </iframe>
        <script type='text/javascript'> 

            $('#iframe1').ready(function()
            {
            console.log($('#iframe1').contents().find("#testDiv").html());
            });
        </script>
    </body>
</html>

IFrame.html :

<!DOCTYPE html>
<html>
    <head>
        <title>Iframe</title>
    </head>
    <body>
        <div id="testDiv">
            Works!
        </div>
    </body>
</html>

All i am getting in console log is 'undefined' instead of 'Works!'. What am I doing wrong?

Thanks in advance.

解决方案

Try using load instead of ready.

$('#iframe1').load(function(){
    console.log($('#iframe1').contents().find("#testDiv").html());
});

这篇关于使用jquery从父页面访问子IFrame中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆