我不知道这段代码做错了什么,我在网上查了一下,我所看到的就是将 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
侦听器 ,然后在尝试记录之前检查数据属性是否已定义。