The script tag inside the iframe is executed on the parent dom

I am writing a jquery script inside my iframe to hide h1 inside the iframe

<iframe id = "preview" width="800" height="500">   
</iframe>

 <script>
var H = "<html><head><script>$(\'#hh\').toggle();<";
H+= "/script></head><body><h1 id='hh'>JavaScript</h1></body></html>";

 var previewFrame = document.getElementById("preview");
 var preview =  previewFrame.contentDocument ||  previewFrame.contentWindow.document;
 preview.open();
 preview.write(H);
 preview.close();
  </script>

but the script cannot see the elements inside the iframe when I moved the element with id = 'hh' from the iframe, the script is working, can anyone help me?

+4
source share
1 answer

It looks like you are trying to use jQuery inside an iframe for a script that you put in an iframe, but you don't have jQuery in the iframe. An IFrame is a completely different execution context. If you want to use jQuery there, you need to download jQuery.

, script, DOM <head>. DOM . script <body> (, </body>), $(document).ready(...) script DOM.

, , :

  • jQuery iframe, .
  • jQuery <script>. .src, script .
  • $(document).ready(function() { your code here}).
  • <script> </script>, JS, '<scr' + 'ipt>'.

:

var H = '<html><body><h1 id="hh">JavaScript</h1>';
H += '<scr' + 'ipt src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></scr' + 'ipt>';
H += '<scr' + 'ipt>$(document).ready(function() {';
H += '$("#hh").hide();';
H += '});</scr' + 'ipt>';
H += '</body></html>';

var previewFrame = document.getElementById("preview");
var preview =  previewFrame.contentDocument ||  previewFrame.contentWindow.document;
preview.open();
preview.write(H);
preview.close();

H, .

: http://jsfiddle.net/jfriend00/8L3KT/


FYI, . HTML JS .

+4

Source: https://habr.com/ru/post/1543256/


All Articles