我有一个 contenteditable div,您可以在其中输入 javascript,该 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);
});
到目前为止,这有效。但生成的脚本没有任何效果。浏览器一定无法识别该脚本,因为它在页面加载时不存在?如何让脚本在不重新加载页面的情况下生效?
注意:脚本上的类型/简写是因为我使用的是 plugin which converts shortand words到实际的 JavaScript 中。因此,用户只需要在 contenteditable div 中写入简写,插件就会将其转换为 JS。这可能会加剧问题?
最佳答案
我认为修改现有的 <script>
不起作用元素。如果您希望执行脚本,则需要添加一个新元素。
$('#save-script').click(function() {
var script = $('#script-generator').html();
$("#script").text(script);
ShortHand.parseScripts();
});
关于javascript - 动态生成的脚本不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22423678/