jQuery - HTML中的脚本标记由jQuery解析而不执行 [英] jQuery - script tags in the HTML are parsed out by jQuery and not executed

查看:105
本文介绍了jQuery - HTML中的脚本标记由jQuery解析而不执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似的HTML页面:

<html>
<body>
<div id='something'>
    ...
    <script>
    var x = 'hello world';
    </script>
    ...
</div>
</body>
</html>

在另一页上,我这样做:

$.ajax({
    url: 'example.html',
    type: 'GET',
    success: function(data) {
        $('#mydiv').html($(data).find('#something').html());
        alert(x);
    }
});

然而,jQuery没有在第一个文件中执行javascript,即使文档说它确实如此。我怎么能这样做?

jQuery, however, is not executing the javascript in the first file, even though the documentation says it does. How can I make it do that?

编辑:不幸的是,在我正在研究的现实世界中,我无法控制包含的内容页面有。我们在同一个域上,但我无法修改它输出的代码,因为它是我们的IT部门不会让我们修改的打包产品。

推荐答案

正如Pointy 指出 out(原谅双关语),当你将HTML传递给<$ c时,jQuery会混淆SCRIPT标签$ C> $()。它不会删除它们 - 它只是将它们添加到从HTML生成的DOM集合中。您可以像这样执行脚本:

As Pointy pointed out (excuse the pun), jQuery messes with the SCRIPT tags when you pass HTML to $(). It doesn't remove them though -- it simply adds them to the DOM collection produced from your HTML. You can execute the scripts like so:

$.ajax({
    url: 'example.html',
    type: 'GET',
    success: function(data) {

        var dom = $(data); 
        $('#mydiv').html(dom.find('#something').html());
        dom.filter('script').each(function(){
            $.globalEval(this.text || this.textContent || this.innerHTML || '');
        });
    }
});

这篇关于jQuery - HTML中的脚本标记由jQuery解析而不执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆