How do I make an HTML button’s onclick event trigger one of two different functions at random?
How do I make an HTML button’s onclick
event trigger one of two different functions at random?
I’m using PHP on the server, and jQuery on the client. Using this code when i click the button image nothing happens...
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" />
As Jon said, attach one function to the button’s onclick
event, then have that function call one of your two functions randomly.
In jQuery, you could do it like this:
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]();
}
);
Say you have code like:
$('#button').click(function() {
// handler 1 code
});
$('#button').click(function() {
// handler 2 code
});
You would change it to:
$('#button').click(function() {
if(Math.random() < 0.5) {
// handler 1 code
} else {
// handler 2 code
}
});
Attach one event handler, and make that single handler decide what to do randomly.
For example, in C# you might do:
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
}
}
The details may vary in jQuery / JavaScript, but basically you'd still make onclick
call a single function which then worked out what to do.
$('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));
Haven't tested, hope it works. How it works: randomFunction
returns a function which itself calls one of the arguments to randomFunction
randomly.
This approach obviously only makes sense if you have several events, there you want a random function to respond to them. If it's only this single event, than using one of very versions above is simpler.
精彩评论