这似乎有点矫枉过正,我想重构这个...任何建议
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".
| 归档时间: |
|
| 查看次数: |
580 次 |
| 最近记录: |