我不知道這段程式碼做錯了什麼,我上網查了一下,我所看到的就是將 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>
感謝您的幫忙:)
您可能意味著
select
有一個change
偵聽器 ,然後在嘗試記錄之前檢查資料屬性是否已定義。