5

私が使用しているウィジェット形式のため、iframe 内に複数の iframe が埋め込まれたページがあります。コードは膨大で扱いにくいので貼り付けませんが、基本的には次のとおりです。

<html>
    <head></head>
    <body>
        <iframe>
            <html>
                <head></head>
                <body>
                    <iframe>
                        <html>
                            <head></head>
                            <body>
                                <iframe>
                                    <html>
                                        <head></head>
                                        <body>
                                        blah
                                        </body>
                                    </html>
                                </iframe>
                            </body>
                        </html>
                    </iframe>
                </body>
            </html>
        </iframe>
    </body>
</html>

ただし、使用するページとテンプレートによっては、iframe が多かったり少なかったりする場合があります。

したがって、最も埋め込まれた iframe 内から、このページのすべての iframe の ID を取得しようとしています。

これはjQueryで可能ですか?コードのスニペットをいくつか試しましたが、うまくいきませんでした:

$('iframe', window.parent.document).each(function() {
    console.log($(this).attr("id"));
});

$('iframe', parent.document).each(function() {
    console.log($(this).attr("id"));
});

$('iframe').each(function() {
    console.log($(this).attr("id"));
});

これらの出力は単一の ID 文字列です。残念ながら、これは私が制御しようとしている iframe ではありません。

前もって感謝します、

4

3 に答える 3

0

最も埋め込まれた iframe から:

var ids = (function up( context, ids ){ 
   ids = ids || []; 
   // proceed if we're not at the top window yet
   if( context !== window.top){
      // point context to parent window (or top if no parent).
      context = context.parent || window.top; 
      // get the id of the first iframe in parent window; 
      // this will break if there are sibling iframes
      ids.push(context.document.getElementsByTagName('iframe')[0].id); 

      // recursive call to traverse parents          
      return up(context, ids); 
   } else {
      // otherwise return the list of ids
      return ids; 
   }
   }(this)); // 'this' is the initial context - current window

   console.log( ids );
于 2013-09-19T08:32:27.913 に答える