问题
I am trying to make a one of a series of divs appear randomly with jquery along with it's navigation link(i.e. If services gets pick, the services link will unfade). I have found this code various times in various forms on this forum, and was wondering if and how I could adapt it to what I would want.
var services = $(random1, random2, random3).get()
.sort(function(){return Math.round(Math.random());}).slice(0,1)
$(services)/*Conditions here*/;
var random1 = false;
var random2 = false;
var random3 = false;
This is a really bad example, I know. I am get lost on it. Any help would be greatly apprecaited, and thanks in advance.
EDIT: I did try to make an easier comparison earlier, but here is what I am actually working on. I tried to adapt the code from @pst.
var v1 = "hello"
var v2 = "world"
var control = [
function (v) { v1 = v },
function (v) { v2 = v }
]
$.each(control, function (i, fn) {
fn(false)
})
$("a#random-btn").click(function(event){
event.preventDefault();
var trueIdx = Math.floor(control.length * Math.random())
props[trueIdx](true)
if (v1 === true){
$("div#small-obstacles-contain a#1 span").stop().animate({opacity: 1,}, '100').animate({opacity: 0,}, '100');
$("div#small-obstacles-contain a#2 span").stop().animate({opacity: 1,}, '100').animate({opacity: 0,}, '100');
}
if (v2 === true){
$("div#small-obstacles-contain a#3 span").stop().animate({opacity: 1,}, '100').animate({opacity: 0,}, '100');
$("div#small-obstacles-contain a#4 span").stop().animate({opacity: 1,}, '100').animate({opacity: 0,}, '100');
}
});
回答1:
I suspect this is really an X-Y problem, this address the title, but may miss "what is really desired at the end of the day". In any case, the concepts are somewhat adaptable.
I wouldn't use variables, but rather an an array/object.
Let's assume an object (so we can have different names used :-) and then a "control" sequence for which properties are eligible to be toggled:
var obj = {a: true, b: false, "3": false, hello: "world"}
var control = ["a", "b", "3"]
// set all to false -- noet that $.each != $().each !!!
$.each(control, function (i, prop) {
obj[prop] = false
})
// set one true
var trueIdx = Math.floor(control.length * Math.random())
obj[control[trueIdx]] = true
However, if variables were really desired for some reason then closures could be used (this could also be used to run arbitrary code for a particular binding):
var v1 = "hello"
var v2 = "world"
var control = [
function (v) { v1 = v },
function (v) { v2 = v }
]
// set all to false -- noet that $.each != $().each !!!
$.each(control, function (i, fn) {
fn(false)
})
// set one true
var trueIdx = Math.floor(control.length * Math.random())
props[trueIdx](true)
Happy coding.
来源:https://stackoverflow.com/questions/7869813/making-1-of-6-variables-true-randomly-in-jquery