18.重複除外


再構築:コードの改善
包装し直しましょう
😋妙技
同じ単語を選択してすべて変更する場合は、その単語をドラッグし、ctrl+dを押して下に向かって単語を選択します.

night,dayボタンも文章段落の下に作成したい...



触る「さわる」
🤔 : こんなボタンを1億個作ろうとしたら…?
(1億個のidを作成して一つ一つ修正する必要がある...)
😨
.
.
.
.

this

  <input type="button" value="night" onclick="
  if (this.value == 'night'){
    document.querySelector('body').style.backgroundColor='black';
    document.querySelector('body').style.color='white';
    this.value = 'day';
  } else {
    document.querySelector('body').style.backgroundColor='white';
    document.querySelector('body').style.color='black';
    this.value = 'night';
  }
  ">
thisを使用しても問題ありません.document.querySelector('#night_day2')は自分のことなので、thisを使えばいいです.ラベルのidも削除できます.
これにより、このコードを何度も繰り返し貼り付けても正常に動作します.

var


コードの良い方法は重複を解消することです!!
上記のコードにはdocument.querySelector('body')が繰り返し表示されます.
varを使用して簡潔に作成しましょう.
  <input type="button" value="night" onclick="
  var target = document.querySelector('body');
  if (this.value == 'night'){
    target.style.backgroundColor='black';
    target.style.color='white';
    this.value = 'day';
  } else {
    target.style.backgroundColor='white';
    target.style.color='black';
    this.value = 'night';
  }
  ">