How to load script with jquery.load()?

好久不见. 提交于 2020-01-25 08:52:05

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/5519792/how-to-load-script-with-jquery-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!