繁体   English   中英

JavaScript-从警报到功能

[英]JavaScript - from alert to function

我对学习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]);
}

尝试这个:

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]);
}

您根本没有调用changeCombined()函数。

如果尝试调用函数,则必须使用()

image[0]=changeCombined2();
image[1]=changeCombined1(); 

您只具有image[0]image[1]本身的功能。 所以之后

x = changeCombined2;

x将保留对changeCombined2 函数本身的引用。 因此,现在如果您说x() (或者您的情况是image[0]() ),它将调用 changeCombined2

()将调用函数,并将函数的返回值放入数组元素中。

注意:由于函数没有显式返回任何内容,因此image[0]image[1]将保持undefined

要调用一个函数,您应该使用applycall方法。

您是否尝试过image[whichImage].apply(undefined)而不是alert

感谢所有帮助我克服障碍的人,最大的问题是不给我打电话的新秀错误。 我能够剪辑这些评论,以创建可以正常使用的版本。

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);}; 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM