Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...