【问题标题】:How do I use function arguments in child switch statements?如何在子 switch 语句中使用函数参数?
【发布时间】:2013-06-26 20:02:28
【问题描述】:

在这种情况下,我试图调用shoppingClickHandler(buyItem),期望它运行子switch 语句以将feature 分配为buyItem

但是我返回了错误Uncaught ReferenceError: buyItem is not defined

我应该只向函数发送字符串吗?

function shoppingClickHandler(feature){
    var msg;
    var itemIdentifier = $(this).parent().attr('class');
    switch(feature) {

        case buyItem: msg = "You bought Item #" + itemIdentifier;
        break;

        case tryItem: msg = "You tried Item #" + itemIdentifier + " on";
        break;

        case suggestItem: msg = "You suggested Item #" + itemIdentifier;
        break;

        case giftItem: msg = "You gifted Item #" + itemIdentifier;
        break;

        case add_to_wishlist: msg = "You added Item #" + itemIdentifier + " to your wishlist";
        break;
    }
    makeEntry(msg);
}


//Buy button test
$('.buy').click(function(){
    shoppingClickHandler(buyItem);
})

//Try button test
$('.try').click(function(){

})

//Suggest button test
$('.suggest').click(function(){

})

//Gifting button test
$('.gift').click(function(){

})

//Add to wisthlist test
$('.add_to_wishlist').click(function(){

})

【问题讨论】:

  • 听起来你在寻找字符串
  • buyItem 未定义。除非您没有发布整个代码,否则在该示例中您没有定义名为buyItem 的变量。如果您打算让函数检查字符串,请确保在调用 shoppingClickHandler 函数时在参数周围添加单引号或双引号。

标签: javascript function switch-statement


【解决方案1】:

用作字符串

  case 'buyItem':
  //ets...

【讨论】:

    猜你喜欢
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 2018-08-31
    • 2017-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多