简体   繁体   English

在 IF ELSE 语句的 2 个位置找到了类似的代码块。 考虑重构 JS

[英]Similar blocks of code found in 2 location in IF ELSE statement. Consider refactoring JS

if (notesValue) { document.querySelector(`.card-${domain.id} .add-notes-button`).classList.add('notes-filled'); } else { document.querySelector(`.card-${domain.id} .add-notes-button`).classList.remove('notes-filled'); }

The refactoring is simply done by using the second force param of the toggle Method:重构只需使用toggle方法的第二个参数即可完成:

Element.classList.toggle("className", forceBoolean)
MDN Docs DOMTokenList.toggle() MDN 文档 DOMTokenList.toggle()

const EL_button = document.querySelector(`.card-${domain.id} .add-notes-button`);
EL_button.classList.toggle('notes-filled', notesValue);
document .querySelector(`.card-${domain.id} .add-notes-button`) .classList .toggle('notes-filled', notesValue);

Using toggle is a good idea but for a more general case where a method like that doesn't exist you could choose which method on the object to target eg:使用切换是一个好主意,但对于不存在这样的方法的更一般的情况,您可以选择对象上的哪个方法作为目标,例如:

document.querySelector(`.card-${domain.id} .add-notes-button`)
  .classList[notesValue ? 'add' : 'remove']('notes-filled');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM