我有一个toggleClass
函数,它基本上会反转if..else
中的类,具体取决于状态是删除还是重置。任何人都可以提出任何关于如何改进它以使其更好的建议吗?
JS
/**
* Uses the click events currentTarget as the element and a state string
* to work out how the required classes should be toggled.
*
* @param $el - jQuery click event
* @param state - string `reset` or `delete`
*/
toggleClass: function($el, state) {
console.log('toggleClass', state);
if(state === 'delete') {
$el.toggleClass('js-delete-session js-reset-session');
$el.toggleClass('fa-times fa-undo');
} else {
$el.toggleClass('js-reset-session js-delete-session');
$el.toggleClass('fa-undo fa-times');
}
},
答案 0 :(得分:4)
当您在两种状态下切换相同的类时,您不需要单独的状态代码。您甚至可以将这些类放在同一个调用中:
toggleClass: function($el) {
$el.toggleClass('js-delete-session js-reset-session fa-times fa-undo');
},
答案 1 :(得分:2)
切换班级js-delete-session
和js-reset-session
的第一个语句在if
和else
块中都很常见,可以移到if else
之外。< / p>
toggleClass: function($el, state) {
// Common to both delete and reset
$el.toggleClass('js-delete-session js-reset-session');
if(state === 'delete') {
$el.toggleClass('fa-times fa-undo');
} else {
$el.toggleClass('fa-undo fa-times');
}
},
此外,三元运算符可用作if...else
toggleClass: function($el, state) {
$el.toggleClass('js-delete-session js-reset-session');
state === 'delete' ? $el.toggleClass('fa-times fa-undo') : $el.toggleClass('fa-undo fa-times');
},
OR,
toggleClass: function($el) {
$el.toggleClass('js-delete-session js-reset-session fa-times fa-undo');
},