动态生成的脚本无法正常工作

时间:2014-03-15 12:14:58

标签: javascript jquery ajax

我有一个contenteditable div,你键入javascript,输出到一个空脚本标签。

<div contenteditable="true" id="script-generator"></div>
<div id="save-script">Save</div>

<script type="text/shorthand" id="script">
</script>

所以你在div中编写你的脚本,点击保存,我有一些JS获取contenteditable div的html并将其添加到空脚本标签。

$('#save-script').click(function() {
  var script = $('#script-generator').html();
  $('#script').html(script);
});

到目前为止这是有效的。但生成的脚本无效。浏览器必须无法识别脚本,因为它没有在页面加载时出现?如何在不重新加载页面的情况下使脚本生效?

注意:脚本上的类型/缩写是因为我在实际的Javascript中使用了plugin which converts shortand words。因此用户只需要将速记写入contenteditable div,插件就会将其转换为JS。这可能会增加问题吗?

3 个答案:

答案 0 :(得分:3)

我认为它无法修改现有的<script>元素。如果要执行脚本,则需要添加 new 元素。

$('#save-script').click(function() {
    var script = $('#script-generator').html();
    $("#script").text(script);
    ShortHand.parseScripts();
});

答案 1 :(得分:1)

正确 - 您需要创建脚本标记以使其在加载后执行。

$('head').append($('<script />', {html: script}));

...这意味着您可以删除空脚本标记。

答案 2 :(得分:0)

我已经设置了一个类似于您一直在寻找的测试。看看是否有帮助。

Working Demo 测试代码:

<div id="script" style="display:none">
    alert(4+4);
</div>
<input id="sLoad" type="button" value="Load/Execute Script" />

$('#sLoad').click(function(){
    //You may want to append to the head
    $('<script/>').append( $('#script').html() ).appendTo('#script');

});
相关问题