2012-08-15 45 views
1

我试图制作一个Code Playground,如Tinkerbin将Javascript从textarea注入Iframe

它基本上将CSS/HTML/Javascript代码从不同的Textareas中取出并注入到Iframe中。它也应该立即更新Iframe。

但是我有点卡住注入Javascript。


知道,我迄今所做:

(function() { 
    $('.grid').height($(window).height());  

    var contents = $('iframe').contents(), 
     body = contents.find('body'), 
     styleTag = $('<style></style>').appendTo(contents.find('head')); 

    $('textarea').keyup(function() { 
     var $this = $(this); 
     if ($this.attr('id') === 'html') { 
      body.html($this.val()); 
     } 
     if ($this.attr('id') === 'css') { 
      styleTag.text($this.val()); 
     } 
    }); 

})(); 

这确实注入了CSS和HTML,但不是的JavaScript。

我尝试添加

 scriptTag = $('<script></script>').appendTo(contents.find('head')); 

 if ($this.attr('id') === 'javascript') { 
      scriptTag.text($this.val()); 
     } 

但它没有工作


有人能帮助我吗?

+0

无关,但你应该看看这个:http://stackoverflow.com/questions/8004001/how-does-jsfiddle-allow-and-execute-user-defined- javascript-without-being-danger – irrelephant 2012-08-15 07:12:27

回答

1

我认为您可能需要同时注入脚本标记和内容,因为插入<script>标记将导致broswer运行脚本。如果脚本内容稍后插入,则可能无法运行,但我不确定。试着这样说:

$('<script></script>') 
     .text($('theinputselectorhere').val()) 
     .appendTo(contents.find('head')); 
+0

您必须正确设置正确的上下文。或者,您可以直接使用选择器。 – bingjie2680 2012-08-15 06:47:34

+0

如何正确设置上下文? – janesconference 2013-04-24 15:56:32