javascript - 如何在我的 js 代码中使用简写 if else 语句

标签 javascript jquery

我创建了以下 if else 语句,但是 if else 语句太多了。我想学习如何速记?

if(REL == 'Like'){
   $('#Like' + dataid).attr('rel', 'NotLike');
} else if(REL == 'Love') {
   $('#Love' + dataid).attr('rel', 'NotLove');
} else if(REL == 'Unbelievable'){
   $('#Unbelievable' + dataid).attr('rel', 'NotUnbelievable');
} else if(REL == 'Spectacular'){
   $('#Spectacular' + dataid).attr('rel', 'NotSpectacular');
} else if(REL == 'Emotional'){
   $('#Emotional' + dataid).attr('rel', 'NotEmotional');
}

最佳答案

只需检查变量即可。

if (['Like', 'Love', 'Unbelievable', 'Spectacular', 'Emotional'].indexOf(REL) !== -1) {
    $('#' + REL + dataid).attr('rel', 'Not' + REL);
}

对于基于以'Not'开头的字符串的触发器,你可以使用这个

var temp = REL,
    not = 'Not';

if (REL.substring(0, 3) === 'Not') {
    temp = REL.substring(3);
    not = '';
}
if (['Like', 'Love', 'Unbelievable', 'Spectacular', 'Emotional'].indexOf(temp) !== -1) {
    $('#' + REL + dataid).attr('rel', not + temp);
}

带状态保护器的提案

var lastState = '';

function change(state) {
    var temp = state,
        not = 'Not';
    if (state.substring(0, 3) === 'Not') {
        temp = state.substring(3);
        not = '';
    }
    if (['Like', 'Love', 'Unbelievable', 'Spectacular', 'Emotional'].indexOf(temp) !== -1) {
        $('#' + temp + dataid).attr('rel', not + temp);
    }
    return not + temp;
}

// usage always both together:
change(lastState);       // to reset the last state
lastState = change(REL); // call change and save the actual state

关于javascript - 如何在我的 js 代码中使用简写 if else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36971480/

相关文章:

javascript - 重力点不能与其他元素一起正常工作

javascript - 如何在createjs中将鼠标指针位置添加到自定义鼠标指针

javascript - 咕噜声。当包含子文件 (_*.jade) 时编译所有 .jade 文件

javascript - 如何在 Immutable.js 中设置深度嵌套的值?

javascript - 从特定行中删除多个表格单元格

javascript - jquery/javascript : add to array in case tr has certain class

javascript - Array.prototype.forEach 元素的重新赋值

javascript - 具有特定值的隐藏输入 id 属性在 ie7 中返回为未定义

jquery - 允许弹出气泡到 jQuery UI 对话框的 "break out"

jquery - 使用 jquery "html"动态加载表时,网格标题加载在 IE8 中的表底部