0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

JavaScript すっきりリファクタリング 1

Last updated at Posted at 2022-11-23

ネット上で見かけたJavaScriptのコードをリファクタリングしていく企画です。

元コード

食べ物のラジオボタンを選択したら、それに合わせて<select>タグの内容(<option>タグ)が変わる。
細かな仕様として、未選択の<option>タグは常に表示する。

元コード
<ul id="foodList">
  <li>
    <input type="radio" value="fruits" name="foods" id="fruits">
    <label for="fruits">果物</label>
  </li>
  <li>
    <input type="radio" value="vegetables" name="foods" id="vegetables">
    <label for="vegetables">野菜</label>
  </li>
  <li>
    <input type="radio" value="meats" name="foods" id="meats">
    <label for="meats"></label>
  </li>
</ul>

<select id="foodSelect">
  <option value="">未選択</option>
</select>

<script>
const FOOD = {
    "fruits": ["りんご", "みかん", "ぶどう"],
    "vegetables": ["キャベツ", "じゃがいも", "なす"],
    "meats": ["鶏肉", "豚肉", "牛肉"]
};

// イベント部
$('[name="foods"]').on('change', function() {
    let foodSelect = $('#foodSelect');
    let val = $(this).val();
    let html = "";
 
    // 未選択以外を削除
    foodSelect.find('option:not(:first)').remove();
    // カテゴリ一覧を配置
    $.each(FOOD[val], function(i, value){
        html += `<option value="${value}">${value}</option>`;
    });
    foodSelect.append(html);
});
</script>

新コード

イベント部のみの変更です。

新コード
foodList.onchange = function(event){
    foodSelect.replaceChildren(foodSelect[0], ...FOOD[event.target.value].map(v => new Option(v, v)))
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?