开发者

jQuery load() issue with html that contain jQuery plugin

FYI, here is my code:

[index.html]

<script type="text/javascript" src="js/script.js"></script>

[script.js]

$(document).ready(function() {
    $('#buttonEphone').click(function() {
        $('#apDiv2').load("ePhone.html, #content");
    });
});

"ePhone.html" contain some lightbox effect. (making use of code below)

[ePhone.html]

<script type="text/javascript" src="js/prototype.lite.js"></script>
<script type="text/javascript" src="js/moo.fx.js"></script>
<script type="text/javascript" src="js/litebox-1.0.js"></script&g开发者_运维技巧t;

The Litebox plugin also required to add onload="initLightbox()" within the BODY tag of ePhone.html.

From the above code, I can load ePhone.html's content(#content div) to my <div>(apDiv2) of my index.html. However, the lightbox effect is no longer work. I've also try loading the whole html instead of only #content:

$('#apDiv2').load('ePhone.html');

but it still doesn't work.


In Browser, Javascript executes upon certain event. At page loading, after page is loaded, or any defined events.. so on..

But when you try loading the HTML via ajax in some DIV, and that HTML contains some JS, then browser will not execute that JS, because that JS is not registered in DOM of browser.

So, What you can do is, Keep only HTML in ePhone.html, And move out all of the JS script from that page, and keep that JS on index.html. And use live() for binding whatever events you registered in ePhone.html.

That will make it working.

Thanks!

Hussain


you can use getScript function to dinamically load scripts after jquery.load function completed. try this:

$(document).ready(function() {
 $('#buttonEphone').click(function() {
  $('#apDiv2').load("ePhone.html, #content", function(){

   // load complete
   // now dynamically load the script

    $.getScript('js/prototype.lite.js', function() {
     $.getScript('js/moo.fx.js', function() {
      $.getScript('js/litebox-1.0.js', function() {
         // init lightbox here
      });
     });
    });

  });
 });
});


As .load() is a shortcut for .bind('load', handler) and there is issues with using existing functionality with new elements loaded into the DOM via .bind(), try using the .live('load', handler) instead to accomplish your task.

.live() offers the same functionality as .bind() with the added benefit that any elements within the loaded data will be affected by any scripts you currently use.

EDIT

From your comment above on using the <body onload=""> attribute you should probably know this:

"The .ready() method is generally incompatible with the attribute. If load must be used, either do not use .ready() or use jQuery's .load() method to attach load event handlers to the window or to more specific items, like images."

EDIT 2

Try this:

$('#apDiv2').live('load', 'ePhone.html, #content', function(){
    //Add extra stuff here if you need to
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜