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
1.2k views
in Technique[技术] by (71.8m points)

url - How to load script with jquery.load()?

I have a question.

In my file content.html I have script. When load this with the load() function of jQuery, the page shows but the script doesn't work. I think it's because of a selector.

How can I solve that ?

EDIT :

$(document).ready(function(){
$('#content').load('content.html #toLoad', function(){});
})

Thanks

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

When you say "the script doesn't work" do you mean there's javascript in the page you're loading through ajax?

It's not going to work, ever, at least not directly.

You have two choices. Parse out the script from the content you've loaded, and use eval to run it.

A better way is to use $.getScript to load (and execute) javascript. If you want to bind your javascript with the HTML you've loaded, then you need some convention to identify the script. For example you could include a tag in your dynamically loaded html:

<span style="display:none;" id="script">/scripts/somescript.js</span>

Then look for a span with id="script" when you load the content, if you find it, use $.getScript to load the script it identifies.

example...

$.load('content.html #toLoad', function(data){
    var $script = $(data).find('span[id=script]');
    if ($script.length) {
        $.getScript($script.html());
        // remove the span tag -- no need to render it
        $script.remove();
    }
    $('#content').html(data);
});

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

...