3

I am trying to build a HTML, CSS and jQuery (not just JavaScript) editor, and show the rendered content in an iFrame. Although adding HTML, CSS part is easy, I am unable to execute the JavaScript part.

var html = ""; // HTML code
var content = $("#preview").contents().find("body"); // iframe id is 'preview'
content.html(html);

var cssLink = "<style>" + csVal + "</style>"; // cssVal contains css code
var head = $("#preview").contents().find("head");
head.append(cssLink);

var js ='<script>'+jsEditor()+'<\/script>' ; 

// following part is not working
var content = $('#preview').contents();
$content.find('head').append('<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"><\/script>' );             
$content.find('body').append(js );

I am able to execute to core JavaScript using window.eval(), however it is not working for any JS library included, e.g. jQuery etc.

4

1 回答 1

3

我认为你唯一的问题是你的变量命名:

var content = $('#preview').contents();
$content.find('head').append('<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"><\/script>' );             
$content.find('body').append(js );

应该是 ($content ==> 内容)

var content = $('#preview').contents();
content.find('head').append('<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"><\/script>' );             
content.find('body').append(js );

我稍微修改了您的脚本,但只是为 提供了一些预先设定的值htmlcsVal以及来自jsEditor().

这在 Chrome、Safari 和 Firefox 中对我有用,它在 localhost 上的服务器上运行:

HTML:

<html>
    <head>
    </head>
    <body>
        <div>Look at your new iFrame</div>
        <iframe id="preview"></iframe>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
    </body>
</html>

代码(也在html正文中):

$(document).ready(function() {
    var html = "<div>Hello from iframe</div>"; // HTML code
    var content = $("#preview").contents().find("body"); // iframe id is 'preview'

    content.html(html);

    var csVal = "div { color: red; font-size: 40px;}";
    var cssLink = "<style>" + csVal + "</style>"; // cssVal contains css code
    var head = $("#preview").contents().find("head");
    head.append(cssLink);

    var jsCode = "alert('you are in the iframe')";

    var js ='<script>'+jsCode+'<\/script>' ; 

    // following part is not working
    var content = $('#preview').contents();
    content.find('head').append('<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"><\/script>' );             
    content.find('body').append(js );
});

iFrame 中的结果源:

<html>
    <head>
        <style>
            div {
                color: red;
                font-size: 40px;
            }
        </style>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    </head>

    <body>
        <div>Hello from iframe</div>
        <script>
            alert('you are in the iframe')
        </script>
    </body>

</html>
于 2013-09-08T23:50:32.620 回答