msgbartop
better late than never
msgbarbottom

Sep 19 jquery中实现window.parent.document.getElementById(“myid”)的方法

今天有同事问,如何用jquery实现在iframe中获取父页面中内容元素的方法。

用原生js比较麻烦,要考虑兼容性问题,用jq比较方便,所以搜了一下,没想到结果居然还有错误的方法。

所以在这里留存一份正确方法吧。

他原本是iframe中再套iframe,不过用法大致相同,这里简单用一层iframe来演示一下。

父页面index.html的html结构:

<body>
	<ul id="myul">
		<li><a href="http://www.baidu.com">a</a></li>
		<li><a href="http://www.google.com">b</a></li>
		<li><a href="http://www.sina.com">c</a></li>
	</ul>
	<iframe src="a.html" height="100%" width="100%"></iframe>
</body>

iframe页 a.html中的javascript:

<script language="javascript">
  <!--
	  var a = $("#myul li:last-child a",window.parent.document);
	  alert(a.attr("href"));
  //-->
</script>

作用是在a.html中获取index.html中最后一个li标签中的a标签的href值。

jquery真的很简单啊,哇哈哈。



Leave a Comment




*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word