2010-08-27 38 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 
     }); 
    }) 
})