jQuery: this random selector is rather predictable
In this fiddle http://jsfiddle.net/Sy开发者_如何学CSRb/40/, I created an array with two elements, #f-ONE and #ONE. There is a function that, when the "start" box is clicked, selects one of the two elements randomly, and, depending on which is chosen, displays either a yellow or reddish box.
However, in actual fact, it is always the yellow box that is selected, so something is not working.
However, the exact same code that selects things randomly works in other contexts (see http://jsfiddle.net/urfXq/96/ ), so I don't know what the problem is...
this:
if ('ran === #f-one') {
should be:
if (ran === 'f-one') {
The way you had it, it will always evaluate to true
, because a non-empty string is always "truthy".
EDIT: Didn't see the toLowerCase()
.
Your code is a bit convoluted, here it is cleaned up:
var myArray = [];
myArray[0] = "ONE";
myArray[1] = "f-ONE";
//function getRandom to choose a random element from array
function getRandom(array) {
var key = Math.floor(Math.random() * array.length);
return array[key];
}
$(".start").click(function() {
var id = '#' + getRandom(myArray;
$(id).show();
});
And here it is on jsfiddle: http://jsfiddle.net/SySRb/67/
Oh and the actual problem was in the 'asdf ==== asdf' that is a string and a non-empty string will always be true.
精彩评论