簡體   English   中英

如何使HTML按鈕的onclick事件隨機觸發兩個不同的函數之一?

[英]How do I make an HTML button’s onclick event trigger one of two different functions at random?

如何使HTML按鈕的onclick事件隨機觸發兩個不同的函數之一?

我在服務器上使用PHP,在客戶端上使用jQuery。 單擊按鈕圖像時使用此代碼沒有任何反應......

function a(){  
    alert('A got called!');
}

function b(){  
    alert('B got called!');  
}  

$('#button').bind('click', function(){  
    var rnd = Math.floor(Math.random() * 2);  
    if(rnd)  
       a();  
    else  
       b();  
});

.........

< "base_url().'images/free.png';" rel="nofollow" border='0' align='center' alt="FREE"  id="button"   />

正如Jon所說,將一個函數附加到按鈕的onclick事件,然后讓該函數隨機調用你的兩個函數之一。

在jQuery中,你可以這樣做:

function a(){
    alert('A got called!');
}

function b(){
    alert('B got called!');
}

$('#your_buttons_id_attribute').click(
    function(){
        var functions = [a,b];
        var index_of_function_to_call = Math.round(Math.random());
        functions[index_of_function_to_call]();
    }
);

假設您有以下代碼:

$('#button').click(function() {
    // handler 1 code
});

$('#button').click(function() {
    // handler 2 code
});

你會把它改成:

$('#button').click(function() {
  if(Math.random() < 0.5) {
    // handler 1 code
  } else {
    // handler 2 code
  }
});

附加一個事件處理程序,並使該單個處理程序決定隨機執行的操作。

例如,在C#中你可能會這樣做:

private readonly Random rng = new Random();
...
button.Click += TakeRandomAction;
...
private static void TakeRandomAction(object sender, EventArgs e)
{
    if (rng.Next(2) == 0)
    {
        GiveUserPony();
    }
    else
    {
        NukePlanetFromOrbit(); // It's the only way to be sure
    }
}

jQuery / JavaScript中的細節可能會有所不同,但基本上你仍然可以通過onclick調用一個函數然后解決該怎么做。

$('button').bind('click', function(){
    var rnd = Math.floor(Math.random() * 2);
    if(rnd)
       AnswerForEverthing();
    else
       WhatAmountOfWoodWouldAWouldchuckChuck();
});
function randomFunction() {
    var args = arguments;
    return function() {
        args[Math.floor(Math.random()*args.length)]();
    };
}

$('#id').click(randomFunction(functionOne, functionTwo));

沒有測試過,希望它有效。 工作原理: randomFunction返回一個函數,該函數本身隨機調用randomFunction一個參數。

這種方法顯然只有在你有幾個事件時才有意義,你需要一個隨機函數來響應它們。 如果它只是這個單一的事件,那么比使用上面的一個版本更簡單。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM