2

親コンテナーから iframe のコンテンツを変更し、iframe から親コンテナーのコンテンツを変更する簡単なテストを作成しようとしています。これが私がこれまでに持っているものです:

first.html:

<!doctype html>
<html>
  <head>
    <title>First</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript" src="shared.js"></script>
    <script type="text/javascript" src="first.js"></script>
  </head>
  <body>
    <h1>First</h1>
    <iframe src="http://localhost:3000/second.html"></iframe>
  </body>
</html>

second.html:

<!doctype html>
<html>
  <head>
    <title>Second</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript" src="shared.js"></script>
    <script type="text/javascript" src="second.js"></script>
  </head>
  <body>
    <h1>Second</h1>
  </body>
</html>

共有.js:

function modifyContent(targetContainerElement, targetSelector, sourceString) {
  $(targetContainerElement).find(targetSelector).html("Modified by " + sourceString + "!");
}

first.js:

$(document).ready(function() {

  var iframe = $("iframe");
  modifyContent(iframe.contents(), "h1", "First");
});

second.js:

$(document).ready(function() {

  if (!top.document)
    return;

  modifyContent(top.document.body, "h1", "Second");
});

コードを実行するには、 を使用python -m SimpleHTTPServer 3000して に移動しlocalhost:3000/first.htmlます。最初のヘッダーが変更され、「Modified by Second!」と表示されます。しかし、2 番目のヘッダーには「Second」とだけ表示されます。ここで何が欠けていますか?

4

1 に答える 1

2

完全にロードされたら、iframe 内の h1 タグを変更してみてください。

$(document).ready(function() {

  var iframe = $("iframe");
  iframe.load(function ()
  {
    modifyContent(iframe.contents(), "h1", "First");
  });
});

さらに、書き直すべきだと思いますmodifyContent

function modifyContent(isJquery, targetContainerElement, targetSelector, sourceString) 
{
  if ( isJquery )
    targetContainerElement.find(targetSelector).html("Modified by " + sourceString + "!");
  else
    $(targetContainerElement).find(targetSelector).html("Modified by " + sourceString + "!");
}

すでにjqueryオブジェクトであるため、 $() でラップする必要はありtargetContainerElementません。

于 2012-11-12T07:06:50.730 に答える