Hello.

There is an iframe that is created as a result of loading the page.

var object_preview = $('#preview'); var iframe = $('<iframe id="preview_frame">'), iframe_body, iframe_head; object_preview.html(iframe); setTimeout(function() { var doc = iframe[0].contentWindow.document; iframe_body = $('body', doc); iframe_head = $('head', doc); }, 1); 

When a certain button is clicked, the JS code (jQuery) is inserted into the head tag of this iframe, which must be executed inside the iframe tree.

Button click handler:

 $('#run').click(function() { iframe_body.append('<script type="text/javascript">\ $(document).ready(function() {\ $(".test").click(function() { alert(true); });\ });\ </script>'); }); 

At the moment the code is not executed, how can this be implemented?

The element with the test class is inside the iframe tree; The code must also be executed inside the iframe, and not on the entire page.

HTML structure:

alt text

  • why do you need to execute code inside iframe? Is it really necessary? if yes then document.createElement('script') and add it with the child to the iframe head, - zb '25
  • and $ (document) .ready () is meaningless to do. - zb '
  • @eicto, tried to do as you said, create an element when clicking on the button with the identifier run, but, unfortunately, everything remained the same. About window. $ It is possible in more detail? - evansive
  • @eicto, thank you so much. Transform a comment in response, I will put a tick. - evansive

1 answer 1

jQuery must be loaded into iframe.

 var object_preview = $('#preview'); var iframe = $('<iframe id="preview_frame">'), iframe_body, doc, iframe_head; object_preview.html(iframe); setTimeout(function() { doc = iframe[0].contentWindow.document; var jQueryScript=doc.createElement('script'); iframe_body = $(doc.body); iframe_head = $(doc.head); $(jQueryScript).appendTo(doc.head); jQueryScript.src='//code.jquery.com/jquery-git2.js'; var button=$("<button>").addClass('test').text('test').appendTo(iframe_body); }); $('#run').click(function() { var script=doc.createElement('script'); iframe_body.append(script); script.innerHTML='$(".test").click(function() { alert(true); });'; $(this).hide(); //потому что два раза добавлять сюда нельзя. }); 

http://jsfiddle.net/oceog/85Gbx/