开发者

how to execute jquery code one by one?

how to execute jquery code one by one? I want first do "function 1", when finish the job. then do "function 2"...

Thanks.

<script type="text/javascript">
jQuery(document).ready(function(){
  $(document).ready(function(){ 
    //function 2, jqeury.ajax  
  })开发者_如何转开发;  
  $(document).ready(function(){ 
    //function 3, jqeury.json 
  });  
  $('#col').load("home.html"); 
    //function 4, jqeury.load
  });  
});
</script>
<script type="text/javascript">
jQuery(document).ready(function(){
  //function 1,  a jquery slider plungin
});
</script>


You don't need so many document ready calls. One will suffice

If you mean you want to call each method after one has received the response from the AJAX calls you are making, put the code in the callback;

$(document).ready(function(){
    one(); //call the initial method
});

function one(){
   $.get('url', {}, function(data){
      two(); //call two() on callback
   })
}

function two(){
   $.getJSON('url', {}, function(data){
       three(); //ditto
   })
}

function three(){
   $('#selector').load('url');
}

The docs

http://api.jquery.com/jQuery.get/

http://api.jquery.com/jQuery.getJSON/

http://api.jquery.com/load/


Instead of using more than one document.ready() use callback functions as below.

<script type="text/javascript">
function ajaxfun() {
    //function 2, jqeury.ajax  
    //in ajax callback call the jsonfun();
}  
function jsonfun(){ 
    //function 3, jqeury.json 
    //after json function add the next function in it callback.
}  
</script>
<script type="text/javascript">
jQuery(document).ready(function(){
  //function 1,  a jquery slider plungin
  //Call ajaxfun() here to execute second.
});
</script>


It looks like you are doing three ajax calls. Since jQuery 1.5, we now have a Deferred object (technically a jqXHR object) returned from ajax calls, so you can chain them like this:

$(function() { // this is a document ready function.  it's all you need.
    $.ajax(/* your ajax specs */).done(function() {
        $.getJSON('somepath').done(function() {
            $('#container').load('etc.');
        });
    });
});


use setTimeout function

function f1(para) {
  // ...
  // do work;
  setTimeout(f2, 10);
}

function f2() {
  // ...
  // do work
  setTimeout(f3, 10);
}


<script type="text/javascript">

jQuery(document).ready(function(){
  function2(){  //declare what function 2 will do here
    //function 2, jqeury.ajax  
  } 
  function3(){ 
    //function 3, jqeury.json 
  }  
  $('#col').load("home.html"); 
    //function 4, jqeury.load
  });  
});
</script>
<script type="text/javascript">
jQuery(document).ready(function(){
  //function 1,  a jquery slider plungin

  function2(); // execute function 2 after 1
  function3();
});
</script>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜