2012-03-11 45 views
0

我有一些代碼在 - $(document).ready(function() { - 洗牌的東西,當頁面加載時觸發代碼,但我想要做的是添加一個按鈕,所以這個函數運行,每次我按下按鈕,我怎麼能實現這一點,謝謝?Document.ready函數

+0

你嘗試過什麼?只需將代碼放置在按鈕的單擊事件處理程序中即可。 – 2012-03-11 03:44:42

回答

3

您可以將「隨機播放」代碼保存爲函數,並從代碼庫的其他部分調用它。

var foo = function() { 
    // code that shuffles stuff around 
}; 

$(document).ready(function() { 
    foo(); 
    // other stuff 
}); 

$('#mybutton').click(foo); 
//or 
$('#mybutton').click(function() { 
    foo(); 
    // other stuff. 
}); 
3
function shuffleStuffAround() { 
    // truffle shuffle 
} 

$(function($) { // DOM ready 
    shuffleStuffAround(); 

    $("#some-button").click(function() { 
     shuffleStuffAround(); 
     return false; // you probably want this 
    }); 
}); 
+1

松露洗牌+1 – 2012-03-11 03:43:51

0

你可以簡單的重構,你在準備功能碰上自己的功能和調用在按鈕的單擊事件的代碼:

$(document).ready(function(){ 
    codeToRun(); 
    $('.button').click(function(){codeToRun()}); 
}); 

function codeToRun(){ 
    // do work 
} 
+0

非常感謝您 – user1259527 2012-03-11 04:30:15

相關問題