如何使用jquery.load()加载脚本? [英] How to load script with jquery.load()?

查看:146
本文介绍了如何使用jquery.load()加载脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题.

在我的文件content.html中,我有脚本. 当使用jQuery的load()函数加载它时,页面显示,但是脚本不起作用.我认为是因为有选择器.

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.

我该如何解决?

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

谢谢

推荐答案

当您说脚本不起作用"时,是否表示要通过ajax加载的页面中包含javascript?

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.

您有两个选择.从您加载的内容中解析脚本,然后使用eval来运行它.

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

更好的方法是使用$.getScript加载(并执行)javascript.如果要将JavaScript与已加载的HTML绑定,则需要一些约定来标识脚本.例如,您可以在动态加载的html中添加标签:

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>

然后在加载内容时查找id =" script"的跨度,如果找到它,请使用$.getScript加载它标识的脚本.

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.

示例...

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

这篇关于如何使用jquery.load()加载脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆