使用JavaScript從我的HTML中檢索資料值並將其列印到控制台
P粉381463780
P粉381463780 2024-03-31 13:31:58
0
1
410

我不知道這段程式碼做錯了什麼,我上網查了一下,我所看到的就是將 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粉381463780
P粉381463780

全部回覆(1)
P粉682987577

您可能意味著 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);
}
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!