开发者

Issues using $.ajax

I want to load the lightbox jav开发者_高级运维ascript only when a certain condition is satisfied so I'm loading it using $.ajax like so:

$.ajax({ url: "../static/js/lightbox.js", dataType: 'script', cache: true, success: function() {
    alert('loaded');
    $("a.lightbox").lightbox({
        opacity: "0.6",
        width: "940"
    });
}});

I see the "loaded" alert but the lightbox does not work. However, when I load the file directly (script src) from the HTML, lightbox works. How do I fix this?

Many thanks for your help.


You'll want to use $.getScript() for this (shorter, but slightly different caching effect), for example:

$.getScript("../static/js/lightbox.js", function() {
  $("a.lightbox").lightbox({
    opacity: "0.6",
    width: "940"
  });
});


Does the script get properly downloaded? Do you see the 'loaded' alert? If I were you I would put an alert in lightbox.js to see if is properly executed after downloading. Also check for JavaScript errors.


The issue is the js is not still part of the DOM. Its correct that you get the lightbox.js but its not ready for execution. To get a js file dynamically, you will have to use getScript method instead of ajax. Have a look at the API: http://api.jquery.com/jQuery.getScript/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜