在将函数声明为属性时,“函数语句需要名称”

时间:2013-07-24 15:52:46

标签: javascript jquery parameters

还是一个相对新手。对于那个很抱歉。我试图将一个函数声明为另一个函数的属性。我确信我能做到这一点,并且语法是正确的。但我一直得到“功能声明需要一个名字”作为错误;暗示它认为我正在创建一个匿名函数。

这是代码。它在隐藏和显示参数上抛出错误。我错过了什么?

function band(){

var width_offset = {
    high: "left:-376px", 
    low: "up:-200px" ,
}

hide : function(width_offset){ 
                if ($(document).width < 768){
                        $("#band").animate({width_offset.low}, {queue: false, duration: 200});  
                }else{
                        $("#band").animate({width_offset.high}, {queue: false, duration: 200});  
                };
            }

show : function(){ $("#band").animate({left:'0px'}, {queue: false, duration: 200}); }

}

感谢。

2 个答案:

答案 0 :(得分:2)

这不是声明属性,而是声明标签和函数声明(确实需要名称)。

我猜你希望你的其他代码能够band.hide()band.show(),在这种情况下语法是这样的:

var band = (function() {

    var width_offset = {
        high: "left:-376px",
        low: "up:-200px",
    };

    return {
        hide: function(width_offset) {
            if ($(document).width < 768) {
                $("#band").animate({
                    width_offset.low
                }, {
                    queue: false,
                    duration: 200
                });
            } else {
                $("#band").animate({
                    width_offset.high
                }, {
                    queue: false,
                    duration: 200
                });
            };
        },

        show: function() {
            $("#band").animate({
                left: '0px'
            }, {
                queue: false,
                duration: 200
            });
        }

    };
})();

答案 1 :(得分:0)

你不能在JavaScript中做这样的事情:

{"up:-200px"} != { up: '-200px' } # Not equivalent!

相应地更改您的代码:

function band() {

  var width_offset = {
    high: { left: "-376px" }, 
    low:  { up:   "-200px" }
  };

  return {
    hide: function(width_offset) {  
      if ($(document).width < 768) {
        $("#band").animate(width_offset.low, {queue: false, duration: 200});  
      } else {
        $("#band").animate(width_offset.high, {queue: false, duration: 200});  
      }
    },
    show : function() {
      $("#band").animate({left:'0px'}, {queue: false, duration: 200}); 
    }
  }
}