So I'm currently working on an editor with a preview where it uses Ace and a jQuery generated iFrame to preview the coding written in the Ace textarea thingy in the iFrame. It works fine, but the scripts that I write there are not loading (specifically talking about jQuery/JS).
So here is my markup:
<div class="box" id="snippet">
<input type="text" name="name" class="appname" id="appname" placeholder="App name" />
<div class="snippettext apptext" id="editor">Write code here!</div>
<textarea id="editorhidden"></textarea>
<div id="previewcode">
</div>
</div>
And here is my jQuery/javascript:
$(document).ready(function(){
var editor = ace.edit("editor");
editor.setTheme("ace/theme/monokai");
editor.getSession().setMode("ace/mode/javascript");
var $frame = $('<iframe id="previewframe">');
$('#previewcode').html($frame);
setTimeout( function() {
var doc = $frame[0].contentWindow.document;
var $body = $('body',doc);
$body.html(editor.getValue());
$frame.contents().find('body').prepend('<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"><\/script>').end();
}, 1 );
$(".updatepreview").click(function(){
var doc = $frame[0].contentWindow.document;
var $body = $('body',doc);
$body.html(editor.getValue());
$frame.contents().find('body').prepend('<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"><\/script>').end();
$(".loadingimage").hide();
});
});
I guess there is something about processing jQuery with jQuery, but I can't really figure out how to fix it. Any help is appreciated - thanks :).
I tested this and it worked. Firebug doesn't show the script tag in the head of the iframe, but the alert() call ensures that jQuery is actually loaded.
<p id="foo">
</p>
<script>
$(document).ready(function(){
var $frame = $('<iframe id="previewframe">');
$('#foo').html($frame);
setTimeout( function() {
var doc = $frame[0].contentWindow.document;
var $body = $('body',doc);
$(doc).contents().find("head").append('<scr' + 'ipt type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"><\/scr' + 'ipt>');
// $body.html('<p>content here</p><scr' + 'ipt type="text/javascript">alert(jQuery);<\/scr' + 'ipt>');
// Instead of putting some random html in the body, put from the editor
$body.html(editor.getValue());
}, 1 );
});
</script>
Here is a fiddle .
This thread has a similar subject, so you could get some more feedback on this.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.