Javascript $.html将脚本呈现为内容

Javascript $.html将脚本呈现为内容,javascript,jquery,html,dom-manipulation,dynamic-loading,Javascript,Jquery,Html,Dom Manipulation,Dynamic Loading,对于一个项目,我正在动态加载由html和javascript组成的内容。到目前为止,我一直在使用jquery 1.8.3,但在清理过程中,我想更新到1.10.1。 我已经将问题缩小到在content div上使用$.html()函数的方式 在jquery 1.8.3中: var content = $("#content"); contentDiv.html("<script> alert('Testing'); </script>") 加载的页面包含,,它作为字符串存

对于一个项目,我正在动态加载由html和javascript组成的内容。到目前为止,我一直在使用jquery 1.8.3,但在清理过程中,我想更新到1.10.1。 我已经将问题缩小到在content div上使用$.html()函数的方式

在jquery 1.8.3中:

var content = $("#content");
contentDiv.html("<script> alert('Testing'); </script>")
加载的页面包含,,它作为字符串存储在变量视图中

<h1>New Content</h1>
<div id="newContent"></div>
<script>
function View(){
    this.InitializeView = function(model){
        //code
    }

    this.UpdateView = function (model){
        //code
    }
 }
 </script>
新内容
函数视图(){
this.InitializeView=函数(模型){
//代码
}
this.UpdateView=函数(模型){
//代码
}
}

当我们将代码放入页面的
标题时,浏览器似乎检测到字符串内部的
(脚本结束标记)作为真正的结束

这就是在网页()中引发错误的原因:

未捕获的SyntaxError:意外标记非法fiddle.jshell.net/:22

我猜您必须将javascript代码移动到一个单独的文件中,例如
main.js


在本地对其进行了测试,结果表明:

HTML
有关更多信息,请参见。

能否在上制作一个可复制的示例?如果您希望在服务器上的不同文件上制作模板并在加载后显示,我建议您使用backbonejs。我看到您有HTML和一些要执行的方法。backbonejs正是为这类事情而设计的。fiddle:@retanik您的脚本在一个单独的文件中吗?html和带有view类的javascript在另一个文件中。例如/index.html?page=Visualization,加载一些数据并最终加载包含新内容和javascript的Visualization.html。奇怪的是,在1.8.3中,一切都很好,更高版本也可以,但是除了在我的页面中呈现标签的内容之外。替换标记的解决方案对我不起作用,因为我认为问题在于jquery更改$.html()功能的方式。这个问题的解决方案也可以是,转义字符串中的html并在转义时对其进行解码,即解决方案对我不起作用,请参阅我对上述问题的反应
<h1>New Content</h1>
<div id="newContent"></div>
<script>
function View(){
    this.InitializeView = function(model){
        //code
    }

    this.UpdateView = function (model){
        //code
    }
 }
 </script>
<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.10.1.js"></script>
        <script src="main.js"></script>
        <script type="text/javascript">
            setTimeout(function () {
                $("body").text("Testing now from HTML: using <script>");
                setTimeout(function () {
                     $("body").html("<script>alert('This alert will fail.')</script>");
                }, 1000);
            }, 2000);
        </script>
    </head>
    <body></body>
</html>
$(document).ready(function () {
    $("body").html("<h1>Wait one second.</h1>");
    setTimeout(function () {
        $("body").html("<script>alert('Tested')</script>");
    }, 1000);
});
var content = $("#content");

var script = $("<script>");
script.html("alert('Testing');");

content.append(script)
var tagsToReplace = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;'
};

function replaceTag(tag) {
    return tagsToReplace[tag] || tag;
}

function safe_tags_replace(str) {
    return str.replace(/[&<>]/g, replaceTag);
}