我对学习JavaScript的尝试非常新(仅两周),所以我很高兴并且感到很惊讶。
我要做的是按一个按钮,按钮会唤起一个随机图像或div来到前面。我如你所见,我通过从后向前移动元素来使用z-index。
我已经足够创建一个警告,告诉我它确实发现随机函数不能让它激活这个函数(当我将它分配给按钮时,changeCombined函数可以正常工作但是无法获得getImage运行)。
我不确定是否有可能,而且我知道可能有一百种更好的方法可以做到这一点,但一步一步。
function changeZIndex(i,id) {
document.getElementById(id).style.zIndex=i;
};
var changeCombined1 = function() {
changeZIndex(-5,"scene1");
changeZIndex(5,"scene2");
};
var changeCombined2 = function() {
changeZIndex(-5,"scene2");
changeZIndex(5,"scene1");
};
function get_random(){
var ranNum= Math.floor(Math.random()*2);
return ranNum;
}
function getImage(){
var whichImage=get_random();
var image=new Array()
image[0]=changeCombined2;
image[1]=changeCombined1;
alert(quote[whichImage]);
}
答案 0 :(得分:1)
试试这个:
function changeZIndex(i,id) {
document.getElementById(id).style.zIndex=i;
};
function getImage(){
var whichImage=Math.floor(Math.random()*2);
var image=new Array()
image[0]=function() {
changeZIndex(-5,"scene2");
changeZIndex(5,"scene1");
};
image[1]=function() {
changeZIndex(-5,"scene1");
changeZIndex(5,"scene2");
};
image[whichimage]();
alert(quote[whichImage]);
}
答案 1 :(得分:0)
您根本没有调用changeCombined()
函数。
如果您尝试调用这些功能,则必须使用()
image[0]=changeCombined2();
image[1]=changeCombined1();
您拥有image[0]
和image[1]
的功能本身。
所以
x = changeCombined2;
x
将保留对changeCombined2
功能本身的引用。现在,如果您说x()
(或在您的情况下为image[0]()
),它将调用 changeCombined2
。
()
将调用函数并将函数的返回值放入数组元素中。
注意:由于函数未显式返回任何内容,image[0]
和image[1]
将保留undefined
。
答案 2 :(得分:0)
答案 3 :(得分:0)
感谢所有帮助过了我的路障,不要打电话给我的功能的新手错误是最大的问题。我能够通过评论来创建这个版本,并按预期工作。
function changeZIndex(i,id) {
document.getElementById(id).style.zIndex=i;};
function getImage(){
var whichImage=Math.floor(Math.random()*2);
var image=new Array()
image[0]=function() {
changeZIndex(-5,"scene2");
changeZIndex(5,"scene1");
};
image[1]=function() {
changeZIndex(-5,"scene1");
changeZIndex(5,"scene2");
};
image[whichImage].apply(undefined);};