问题
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