重构一大串链式if-else语句

Mat*_*iby 4 jquery

这似乎有点矫枉过正,我想重构这个...任何建议

    if($(this).text() == "Grocery"){
        $(".type_changer").attr("id", "gro");
    }else if($(this).text() == "Restaurant"){
        $(".type_changer").attr("id", "res");
    }else if($(this).text() == "Bar"){
        $(".type_changer").attr("id", "bar");
    }else if($(this).text() == "Pizza Delivery"){
        $(".type_changer").attr("id", "piz");
    }else if($(this).text() == "Quick Service"){
        $(".type_changer").attr("id", "qui");
    }else if($(this).text() == "Retail"){
        $(".type_changer").attr("id", "ret");
    }else if($(this).text() == "Salon"){
        $(".type_changer").attr("id", "sal");
    }
    if($(this).attr("id").slice(-1) == 1){
        $(".number_changer").attr("id", "one1");
    }else if($(this).attr("id").slice(-1) == 2){
        $(".number_changer").attr("id", "two2");
    }else if($(this).attr("id").slice(-1) == 3){
        $(".number_changer").attr("id", "three3");
    }else if($(this).attr("id").slice(-1) == 4){
        $(".number_changer").attr("id", "four4");
    }else if($(this).attr("id").slice(-1) == 5){
        $(".number_changer").attr("id", "five5");}
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 15

看这里,

if($(this).text() == "Grocery"){
    $(".type_changer").attr("id", "gro");
}else if($(this).text() == "Restaurant"){
    $(".type_changer").attr("id", "res");
}else if($(this).text() == "Bar"){
    $(".type_changer").attr("id", "bar");
}else if($(this).text() == "Pizza Delivery"){
    $(".type_changer").attr("id", "piz");
}else if($(this).text() == "Quick Service"){
    $(".type_changer").attr("id", "qui");
}else if($(this).text() == "Retail"){
    $(".type_changer").attr("id", "ret");
}else if($(this).text() == "Salon"){
    $(".type_changer").attr("id", "sal");
}
Run Code Online (Sandbox Code Playgroud)

你必须考虑所有的重复.什么会遗留下来?对,text和id值:

"Grocery", "gro"
"Restaurant", "res"
"Bar", "bar"
"Pizza Delivery", "piz"
"Quick Service", "qui"
"Retail", "ret"
"Salon", "sal"
Run Code Online (Sandbox Code Playgroud)

让它们保持在一些数据结构中.对象是一个明显的选择.

var types = {
    "Grocery": "gro",
    "Restaurant": "res",
    "Bar": "bar",
    "Pizza Delivery": "piz",
    "Quick Service": "qui",
    "Retail": "ret",
    "Salon": "sal"
}
Run Code Online (Sandbox Code Playgroud)

可以像使用动态键的关联数组一样访问它.现在你可以使用一行:

$(".type_changer").attr("id", types[$(this).text()]);
Run Code Online (Sandbox Code Playgroud)

如何更换第二部分留给你作为锻炼,但它归结为相同.


更新:你似乎很难理解这一点.以下是我方的解释:

$(this).text()返回"Grocery"时,上面会决心

$(".type_changer").attr("id", types["Grocery"]);
Run Code Online (Sandbox Code Playgroud)

types["Grocery"]反过来回报将"gro",因此,它基本上结束了如

$(".type_changer").attr("id", "gro");
Run Code Online (Sandbox Code Playgroud)

$(this).text()"Grocery".

也可以看看:

  • 我沿着这些方向写了一些东西,然后我在视口顶部看到了邪恶的橙色条,告诉我答案已经发布,并且BalusC赢了. (2认同)
  • @Karim:在jQuery标签的正常工作日中经常发生这种情况.这就是为什么我几乎放弃了在工作日回答它并且几乎只在周末回答它的原因,然后有一个*更多的机会,没有其他人发布了合适的答案;) (2认同)