首頁  >  問答  >  主體

使用JavaScript從我的HTML中檢索資料值並將其列印到控制台

我不知道這段程式碼做錯了什麼,我上網查了一下,我所看到的就是將 window.onload = function() 放在程式碼的開頭。但是,該值始終列印為 null,我無法理解為什麼要這樣做。

這是程式碼:

window.onload = function () {
    // Get the select element by its id
    const select = document.getElementById("select-filter");

    // Get the selected option element
    const selectedOption = select.options[select.selectedIndex];

    // Get the data-select value
    const dataSelect = selectedOption.getAttribute("data-sel");

    // Print the data-select value to the console
    console.log(dataSelect);
}
<div class="filter-select-container">
  <!-- filter selector -->
  <div class="filter-selection-container">
    <select name="select-filter" id="select-filter">
      <option value="filter-all">All</option>
      <option value="filter-commercials" data-sel="1">Commercials</option>
      <option value="filter-fiction" data-sel="2">Fiction</option>
      <option value="filter-music-videos" data-sel="3">Music Videos</option>
    </select>
  </div>
</div>

感謝您的幫忙:)

P粉381463780P粉381463780189 天前412

全部回覆(1)我來回復

  • P粉682987577

    P粉6829875772024-04-01 00:13:21

    您可能意味著 select 有一個 change 偵聽器 ,然後在嘗試記錄之前檢查資料屬性是否已定義。

    const select = document.getElementById("select-filter");
    
    select.addEventListener('change', handleChange);
    
    function handleChange() {
      const selectedOption = select.options[select.selectedIndex];
      const dataSelect = selectedOption.getAttribute("data-sel");
      if (dataSelect) console.log(dataSelect);
    }

    回覆
    0
  • 取消回覆