开发者

Calling Multiple Functions from onclick

Okay, so I have a snippet of code from a website containing a button:

    <button type="button"
            onclick="laser(); $.post('sheepDB.php', { vic: vic, num: numVics });">
    Activate Her Powers!
    </button>

However, when I click the button the first time, the first function executes, but if I clic开发者_如何学编程k it a second time, both the first function AND the Ajax call are executed. How do I get onclick to execute them sequentially? (laser() determines the values sent by the Ajax request, so it must be sequential).


Javascript does execute sequentially. However, AJAX is asynchronous (hence the A), which means that Javascript execution continues while the AJAX request is taking place. If you trigger your onclick a second time before the first AJAX request completes, it is possible that the first AJAX request will not complete before the second click (and thus look like it's only happening once).


Well first off all i would not put the code directly in onClick just attach the handler $(selector).click(). regardless your code wont do what you are trying to do... you need something like this as your handler:

$(selectorForButton).click(
  function(e){
  e.preventDefault(); // dont fire the normal event

  /* youll probably have to rework laser if it depends on `this` referring to the dom element    
   * clicked in this example lets say it returns a hash of vic and num vics...
   */
  var _this = $(this);
  var data = laser(this);
  // check if this is already sending a post request
  if(!_this.data('activated')){
     $.post('sheepDB.php', data, function(){
       // this is important - we need to set it to false so we now on the next click that
       // post innt in the process of doing its thing
        _this.data('activated', false);
     });
  }

  return false;
});


$(document).ready(function () {
   $('#yourButtonId').click(function() {
      // collect your values into a json object
      var someData = {
         x: '',
         y: '',
         z: ''
      };

      //execute post
      $.post('someUrl', someData, function(data, textStatus) {
         // callback
      });
   })
})
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜