jquery操作iframe(齐全版,经IE6&IE6+、firefox、chrome测试通过)

  1. 父窗口获取子窗口元素  
    $('@selector', window.frames['@iframeID'].document)
  2. 子窗口获取父窗口元素  
    $('@selector', parent.document)
  3. 子窗口获取子窗口元素  
  4. $('@selector', parent.window.frames['@iframeID'].document)
  5. 附注:出于安全考虑,浏览器不允许脚本跨域访问iframe,谷歌浏览器离线状态下认为脚本访问iframe为跨域访问(跟cookie类似,离线状态下不允许使用cookie)
例子如下:
主窗口:(index.html)
<html>
	<head>
		<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
		<script type="text/javascript">
			$(function(){
				$('#test-button').click(function(){
					//获取左边iframe的元素(父窗口获取子窗口元素 )
					alert($('#test-button', window.frames['left'].document).text());
					//获取右边iframe的元素(父窗口获取子窗口元素 )
					alert($('#test-button', window.frames['right'].document).text());
				})		
			})
		</script>
	</head>
	<body>
		<iframe id="left"  width="30%" height="50%" src="left.html"></iframe>
		<iframe id="right" width="30%" height="50%" src="right.html"></iframe>
		<button id="test-button">test-button-in-index</button>
	</body>
</html>
左边iframe:(left.html)
<html>
	<head>
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
	<script type="text/javascript">
		$(function(){
			$('#test-button').click(function(){
				//获取主窗口iframe的元素(子窗口获取父窗口元素)
				alert($('#test-button', parent.document).text());
				//获取主窗口右边iframe的元素(子窗口获取子窗口元素)
				alert($('#test-button', parent.window.frames['right'].document).text());
			})		
		})
	</script>
	</head>
	<body>
		<button id="test-button">test-button-in-left</button>
	</body>
</html>
右边iframe:(right.html)
<html>
	<head></head>
	<body>
		<button id="test-button">test-button-in-right</button>
	</body>
</html>
本文出自: http://blog.csdn.net/nancle/article/details/10546595


你可能感兴趣的:(jquery,iframe)