我不知道这段代码做错了什么,我上网查了一下,我所看到的就是把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>
感谢您的帮助:)
1条答案
按热度按时间w46czmvw1#
您可能希望
select
上有一个change
listener,然后在尝试记录它之前检查是否定义了data属性。