在javascript中将参数传递给另一个函数

时间:2012-10-27 15:01:22

标签: javascript function arguments

我试图从调用第一个函数“fadesIn()”的按钮传递一些参数到另一个函数“check()”,该函数将继续检查第一个图像是否在第二个图像淡入之前已经消失。要传递参数,我尝试使用

function.apply(this, arguments);

然后使用数组位置调用所需的参数。很遗憾,我无法在我的网页上运行它。我只是在学习,所以我可能会缺少一些东西...非常感谢任何帮助。

var time;

function fadesIn(args){
    fadeOut(arguments[1]);
    check.apply(this, arguments);
    check();
} 

function check(args){
    if(document.getElementById(arguments[1]).style.opacity < 0.1){
        fadeIn(arguments[0]);
        clearTimeout(time);
        return;
    }
    time=setTimeout(function(){check()},100);
}   

fadesIn('pic1', 'pic2');
你们很快就回复了......谢谢..

这是淡入和淡出功能,它们来自youtube上的开发php

var fade_in_from = 0;
var fade_out_from = 10;

function fadeIn(element){
    var target = document.getElementById(element);
    target.style.display = "block";
    var newSetting = fade_in_from / 10;
    target.style.opacity = newSetting;
    // opacity ranges from 0 to 1
    fade_in_from++;

    if(fade_in_from == 10){
        target.style.opacity = 1;
        clearTimeout(loopTimer);
        fade_in_from = 0;
        return false;
    }

    var loopTimer = setTimeout('fadeIn(\''+element+'\')',50);
}

function fadeOut(element){
    var target = document.getElementById(element);
    var newSetting = fade_out_from / 10;
    target.style.opacity = newSetting;
    fade_out_from--;

    if(fade_out_from == 0){
        target.style.opacity = 0;
        target.style.display = "none";
        clearTimeout(loopTimer);
        fade_out_from = 10;
        return false;
    }

    var loopTimer = setTimeout('fadeOut(\''+element+'\')',50);
}

我会玩你的建议。

来自firebug的错误是

TypeError:document.getElementById(arguments [1])为null

1 个答案:

答案 0 :(得分:0)

check();
// and
setTimeout(function(){check()},100);

似乎会引起一些问题。您的check函数需要[至少]两个参数,否则document.getElementById(arguments[1])将返回null并访问该style属性会引发异常。

由于你只使用两个参数,最好不要使用arguments对象,而只是传递两个参数:

function fadesIn(pic1, pic2) {
    fadeOut(pic2);
    check(pic1, pic2);
} 

function check(argOne, argTwo){
    if(document.getElementById(argTwo).style.opacity < 0.1){
        fadeIn(argOne);
        clearTimeout(time);
        return;
    }
    time=setTimeout(function(){check(argOne, argTwo)},100);
}
相关问题