正式参数后jquery / javascript缺失)

时间:2011-08-08 02:58:37

标签: javascript jquery function

您好,我有这段代码:

function getFullnameDetails(mainHeight,upperstyle,type=''){
    setTimeout(function(){fullnameCenter(mainHeight,upperstyle,type='')},2000);
}
function fullnameCenter(mainHeight,upperstyle,type=''){
    var distOfMainAndUpper = mainHeight - upperstyle;
    var mainHalfHeight = mainHeight/2;
    var imageHeight = jQuery("img[rel='fullname']").height(); //there is a delay
    var imageHalfHeight = imageHeight/2;
    var fromImageTopToMainHalf = mainHalfHeight - imageHeight;
    var position = imageHalfHeight+fromImageTopToMainHalf-distOfMainAndUpper;
    if(type == 'big'){ jQuery("#temp .test1").css("bottom",position+"px"); }
    else { jQuery(".test1").css("bottom",position+"px"); }


}
在正式参数之后,它说我失踪了。 这发生在这一行:

function getFullnameDetails(mainHeight,upperstyle,type=''){ //IT HAPPENS HERE! :)
    setTimeout(function(){fullnameCenter(mainHeight,upperstyle,type='')},2000);
}

我在这里做错了什么。

提前感谢您的帮助:)

3 个答案:

答案 0 :(得分:8)

Javascript不支持默认的函数参数值。

你可以做这样的事情(但要警惕意外的'虚假'值):

function getFullnameDetails(mainHeight,upperstyle,type){
  type = type || ''; // if type is 'falsey' (null, undefined, empty string) assign ''
  //...
}

答案 1 :(得分:3)

正如其他答案所指出的,JavaScript不支持函数参数中的默认值。但是,正如其他解决方案中所指出的,使用内联||在传递假名值时无效(例如null0'',{{ 1}},NaN)。更好的解决方案是检查参数是否未定义:

false

或者更一般地说:

type = typeof(type) !== 'undefined' ? type : '';

当然,这意味着将argument_name = typeof(argument_name) !== 'undefined' ? argument_name : default_value;传递给函数将意味着使用默认值 - 但这应该是非常罕见的。

答案 2 :(得分:1)

您是否尝试使用默认参数或其他内容?

类型= ''

这是无效的 - 你不能在这样的函数的参数列表中有一个等号。