我不知道这段代码做错了什么,我在网上查了一下,我所看到的就是将 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);
}
感谢您的帮助:)
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您可能意味着
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); }