如何获取HTML select选中选项的ID?解决控制台输出空行问题
Hey there! Let's fix that issue where you're getting an empty string instead of the selected option's ID. Here's what's going on and how to fix it:
问题根源
Your current code is trying to get e.target.id in the change event—but e.target refers to the <select> element itself, not the selected <option>. Since your <select> tag doesn't have an id attribute set, e.target.id returns an empty string. What you actually need is to access the selected option element and grab its ID.
修正后的代码方案
Here are two working approaches to get the selected option's ID:
方法1:使用selectedOptions
This is the most straightforward way, as selectedOptions returns a collection of selected elements (for single-select dropdowns, it'll be the first item):
var getSelect = document.querySelectorAll('.custom-select'); getSelect.forEach(function(selectElement) { selectElement.addEventListener('change', function(e) { // 获取选中的选项元素 const selectedOption = e.target.selectedOptions[0]; // 获取选项的ID const optionId = selectedOption.id; console.log(optionId); }); });
方法2:使用selectedIndex
If you prefer using the index of the selected option, this works too:
var getSelect = document.querySelectorAll('.custom-select'); getSelect.forEach(function(selectElement) { selectElement.addEventListener('change', function(e) { const select = e.target; // 通过选中索引获取对应选项 const selectedOption = select.options[select.selectedIndex]; console.log(selectedOption.id); }); });
额外优化:初始化时也获取选中ID
If you want to log the selected option's ID when the page first loads (not just on change), you can extract the logic into a reusable function:
function getSelectedOptionId(selectElement) { const selectedOption = selectElement.selectedOptions[0]; // 处理可能没有选中选项的情况(虽然你的下拉默认会选第一个) return selectedOption ? selectedOption.id : null; } var getSelect = document.querySelectorAll('.custom-select'); getSelect.forEach(function(selectElement) { // 页面加载时打印当前选中的ID console.log(getSelectedOptionId(selectElement)); selectElement.addEventListener('change', function(e) { console.log(getSelectedOptionId(e.target)); }); });
内容的提问来源于stack exchange,提问作者Sybrentjuh

