开发者

after ajax call - $(document).ready();?

I've got a problem. this is what I have on my page somewhere in header

 $(document).ready(function(){
       $(".ajax").click(function(e){
       var url = $(this).attr("href");
       var url = url.split("##/");

       if (!url[1]){url[1]=" ";}
       var page = "http://<?php echo $_SERVER[SERVER_NAME]; ?>page.php?ajax=1&what="+url[0]+url[1];
       $("#content").load(page);

       var kkk = 'Asdasdasd';
       });
 });

so, after clicking on  <a href="##/new_page" class="ajax">new</a>, content is being开发者_JS百科 filled with this:

<script> alert(kkk); </script>
<a href="##/old_page" class="ajax">old page</a>

However, alert is not taking in consideration as new page DOES NOT see kkk and neither link which worked on the original page works. Why?


In order for the link to work after loading it again, you probably want a live event. That will watch for any new objects with the ajax class as well instead of just the ones which exist at the time the original document is loaded. And if you need to set anything else up, which would normally be inside document ready, put that in an anonymous function as the second parameter to load() because it isn't guaranteed to have loaded the new content yet otherwise. eg:

   $(".ajax").live('click', function(e){
   var url = $(this).attr("href");
   var url = url.split("##/");

   if (!url[1]){url[1]=" ";}
   var page = "http://<?php echo $_SERVER[SERVER_NAME]; ?>page.php?ajax=1&what="+url[0]+url[1];
   $("#content").load(page, function () { var kkk = 'Asdasdasd'; });

   });

Or as @Levi points out, a .delegate call would accomplish the same thing while being a bit less wasteful: $('content').delegate('.ajax', 'click', function() (...)


The kkk variable is being enclosed in the scope of the document ready function. Move it outside of this function instead:

var kkk = '...';

$(document).ready(function () {
    ...
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜