Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

javascript - How to access frame (not iframe) contents from jQuery

I have 2 frames in one page like this (home.html)

<frameset rows="50%, 50%">
        <frame id="treeContent" src="treeContent.html" />
        <frame id="treeStatus"  src="treeStatus.html" />
</frameset>

and then in one frame (treeStatus.html) I have something like

<body style="margin: 0px">
<div id="statusText">Status bar for Tree</div>
</body>

I want from the top window to manipulate the div located in the child frame via jquery (e.g show and hide).

I have seen several questions like this and they suggest the following

$(document).ready(function(){

            $('#treeStatus').contents().find("#statusText").hide();
     });

I do not know if this works with iframes but in my case where I have simple frames it does not seem to work. The code is placed inside home.html

Here is some output from firebug console

>>> $('#treeStatus')
[frame#treeStatus]
>>> $('#treeStatus').contents()
[]
>>> $('#treeStatus').children()
[]

So how do I access frame elements from the top frame? Am I missing something here?

Answer

After combining both answers here, the correct way is

$('#statusText',top.frames["treeStatus"].document).hide();

For this to work the frame must have the name attribute apart from the id, like this:

<frameset rows="50%, 50%">
            <frame id="treeContent" src="treeContent.html" />
            <frame name="treeStatus" id="treeStatus"  src="treeStatus.html" />
    </frameset>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could grab the Frame and div you are wanting to manipulate and pass it into a variable.

var statusText = top.frames["treeStatus"].document.getElementById('statusText');

Then you can do anything you want to it through jQuery.

$(statusText).whatever();

Though sometimes you just can't get around having to use frames, keep in mind that the <frame> tag is obsoleted in HTML5. If you ever plan on moving up to HTML5, you'll have to use iFrames.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...