我想迭代选择的元素并获取所选的值, 就像电子商务网站的下拉列表一样,用户可以在其中选择他们想要的产品数量。
我尝试使用 querySelectorAll 来获取所有“选择元素”
document.querySelectorAll('.js-quantity-selector')
.forEach((selectedOption)=>{
const optionSelected = selectedOption.options[selectedOption.selectedIndex];
});
这是您要找的吗?
document.querySelectorAll('.js-quantity-selector').forEach((selectElement) => {
// Get the currently selected option
const selectedOption = selectElement.options[selectElement.selectedIndex];
// Get the value of the selected option
const selectedValue = selectedOption.value;
// Alternatively, you can get the text of the selected option
// const selectedText = selectedOption.text;
console.log(`Selected value for ${selectElement.id}: ${selectedValue}`);