Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
97 views
in Technique[技术] by (71.8m points)

javascript - jQuery - script tags in the HTML are parsed out by jQuery and not executed

I have an HTML page like so:

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

On another page, I am doing this:

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

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?

EDIT: Unfortunately in the real world application I am working on I don't have control over what the "included" page has. We are on the same domain, but I can't modify the code that it outputs as it is a packaged product our IT department will not let us modify.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 || '');
        });
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...