今天抽了点时间整理了下有关frameset和iframe之间的一些常见的操作:取值、赋值

先上一个frameset框架

index.html

<frameset rows="100,*">
	<frame src="top.html" id="topFrame" noresize="noresize"/>
    <frameset cols="*,300">
    	<frame src="main.html" id="mainFrame" name="main"/>
        <frame src="right.html" id="rightFrame">
    </frameset>
</frameset><noframes></noframes>

这是常见的布局格式,顶部一个top,下方是左右两个页面

功能一:实现主体布局frame间传值与取值;

如:right.html操作main.html

main.html

main.html
<div id="categoryid"></div>

<hr/>
<a href="javascript;;" id="small">尝试传值给下方iframe</a>   
<a href="javascript:;" id="getsmallElement">尝试获取下方iframe中输入框的内容</a>
<hr/>
<iframe src="small.html" width="600" height="200" name="smallFrame" id="smallFrame"></iframe>
<hr/>
<input type="text" id="inp" value="main.html中的输入框,可以尝试输入内容..." style="width:400px;"/>
<script type="text/javascript">
$(function(){
	$("#small").click(function(){
		var obj;
		//obj=$(document.getElementById('smallFrame').contentWindow.document.body).html(); //对的
		
		obj=$(document.getElementById('smallFrame').contentWindow.document.body);
		$('#small',obj).html('main.html控制当前文档下iframe(small.html)的内容');
		
		return false;
	});
	
	$("#getsmallElement").click(function(){
		var obj=$(document.getElementById('smallFrame').contentWindow.document.body);
		alert($('#inp',obj).val());
		return false;
	});
	
})
</script>

1、给id=categoryid的div传值,在right.html中写到

var obj;
/*设置同级frame中元素的内容*/
obj=$(window.parent.document.getElementById('mainFrame').contentWindow.document.body);
$(obj).find("#categoryid").html('right.html控制main.html的内容');

//或
//$(window.parent.document.getElementById('mainFrame').contentWindow.document.body).find('#categoryid').html('来自right.html的内容');

return false;

2、取id=inp输入框的值,在right.html中写到

var obj=$(window.parent.document.getElementById('mainFrame').contentWindow.document.body);
alert($('#inp',obj).val());
return false;

功能二:实现当前页面对iframe页面的传值与取值

如:main.html对其中iframe(small.html)进行操作

small.html

small.html
<hr/>
<div id="small"></div>
<input type="text" id="inp" value="small.html中的输入框,可以尝试输入些内容..." style="width:400px;">

1、给id=small的div进行传值,在main.html中写到

var obj;
//obj=$(document.getElementById('smallFrame').contentWindow.document.body).html(); //对的

obj=$(document.getElementById('smallFrame').contentWindow.document.body);
$('#small',obj).html('main.html控制当前文档下iframe(small.html)的内容');

return false;

2、取id=inp输入框的值,在main.html中写到

var obj=$(document.getElementById('smallFrame').contentWindow.document.body);
alert($('#inp',obj).val());

主要功能代码:

A、在frameset中获取同级frame对应页面对象中的body

var obj=$(window.parent.document.getElementById('mainFrame').contentWindow.document.body)

B、获取当前页面下iframe对应页面对象中的body

var obj=$(document.getElementById('smallFrame').contentWindow.document.body);

程序演示>>

该方法不能实现跨域