2010-08-27 66 views
0

好了,所以我有一個代碼片段含有一個按鈕一個網站:調用多重功能的的onclick

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

然而,當我點擊按鈕,在第一時間,第一函數執行,但如果我再次點擊它,第一個函數和Ajax調用都會被執行。我如何獲得onclick以順序執行它們? (laser()確定由Ajax請求發送的值,因此它必須是連續的)。

回答

4

Javascript確實按順序執行。但是,AJAX是異步(因此是A),這意味着在執行AJAX請求時Javascript執行會繼續。如果您在第一次AJAX請求完成之前再次觸發onclick,則有可能第一次AJAX請求在第二次點擊之前不會完成(因此看起來像只發生一次)。

1

首先,我不會把代碼直接放在onClick上,只需附加處理程序$(selector).click()。不管你的代碼不會做你正在嘗試做的...你需要像這樣的處理程序:

$(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; 
}); 
0
$(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 
     }); 
    }) 
})