簡體   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'); }

重構只需使用toggle方法的第二個參數即可完成:

Element.classList.toggle("className", forceBoolean)
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);

使用切換是一個好主意,但對於不存在這樣的方法的更一般的情況,您可以選擇對象上的哪個方法作為目標,例如:

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