开发者

How to select the <iframe> that embeds the very b.html with jquery code inside b.html?

开发者 https://www.devze.com 2023-02-01 00:17 出处:网络
<iframe src=\"b.html\"></iframe> <iframe src=\"b.html\"></iframe> <iframe src=\"b.html\"></iframe>
<iframe src="b.html"></iframe>

<iframe src="b.html"></iframe>

<iframe src="b.html"></iframe>

As you can see ,3 <iframe> each embeds the b.html,

b.html:

<script type开发者_Go百科="text/javascript">
//how can I get reference to the very `iframe` that embeds me ??
//for the 1st b.html,select the 1st iframe,and so on...
</script>

How to write the jquery code within b.html ?


First things first place an hidden field within b.html on top of the page or something. Now the value/id for this should be distinct per iframe. AS you serve this page of the server add some code that does this for you. some counter i assume. I would suggest append the counter to the id as follows:

<input type="hidden" id="frame<frame_no>/>

You add a document onload function in your script inside b.html that basically is a jquery selctor that selects this item and then run a parents with a selector that identifies the iframe. For info on parents: http://api.jquery.com/parents/

Now You have a reference to the iframe. Hope that helps and answers your question.

I am not sure whether your b.html page is dynamic enough to this. If that is not the case what you can do is add an hidden field with the same class name and now you have all the hidden fields within the various iframes.

Now to this either you can append an attr like id using jquery by running a each or you can just handle your binds etc inside this each function itself as you can then find the iframe by doing a

$(this).parents(<iframe selector>)

Is this good enough?


I didn't use jquery for a couple of reasons:

  1. I don't know jquery
  2. I don't think it works too well across frames

Should be no conflict with jquery regardless.

The basic idea is to look up to the parent, find all of the iframes and then find the iframe with the contentWindow that is the same as the frame's window.

Here it is running: http://jsbin.com/ewape5/8 (click on the Hello World text in one of the iframes)

Here is the code:

function findIframe() {
  var parentIframes = window.parent.document.getElementsByTagName('iframe');
  var i = parentIframes.length;
  while  (i--) {
    var possibleParent = parentIframes[i];
    if (possibleParent.contentWindow == window) {
      return possibleParent;
    }
  }
  return null;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号