jQuery   发布时间:2022-04-19  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了jquery – 重构大量的链式if-else语句大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
这似乎有点矫枉过正,我想重构这个…任何建议

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");}

解决方法

看这里,

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");
}

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

"Grocery","gro"
"Restaurant","res"
"Bar","bar"
"Pizza Delivery","piz"
"Quick service","qui"
"Retail","ret"
"Salon","sal"

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

var types = {
    "Grocery": "gro","Restaurant": "res","Bar": "bar","Pizza Delivery": "piz","Quick service": "qui","Retail": "ret","Salon": "sal"
}

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

$(".type_changer").attr("id",types[$(this).text()]);

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

更新:你似乎有一个hard time in understanding this.以下是我方的解释:

当$(this).text()返回“Grocery”时,上面将解析为

$(".type_changer").attr("id",types["Grocery"]);

类型[“Grocery”]将依次返回“gro”,因此它基本上结束为

$(".type_changer").attr("id","gro");

当$(this).text()是“Grocery”时.

也可以看看:

> JavaScript Object Notation (JSON) tutorial

大佬总结

以上是大佬教程为你收集整理的jquery – 重构大量的链式if-else语句全部内容,希望文章能够帮你解决jquery – 重构大量的链式if-else语句所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。