在change事件中获取option的ID而非value值的实现方法
获取select选中option的ID属性值
针对需求,这里提供几种可行的方法,在select的change事件中获取选中option的ID属性值:
方法一:jQuery结合:selected选择器
通过:selected选择器定位当前选中的option元素,再获取其id属性:
$("#industry").on("change",function(){ var selectedId = $(this).find("option:selected").attr("id"); // 可根据需求使用selectedId,比如打印输出 console.log(selectedId); });
方法二:原生DOM操作
直接利用原生DOM的属性获取选中项,性能更优:
$("#industry").on("change",function(){ // 获取当前选中的option元素 var selectedOption = this.options[this.selectedIndex]; var selectedId = selectedOption.id; console.log(selectedId); });
方法三:jQuery的prop()方法
对于标准HTML属性,使用prop()方法获取属性值也是合适的选择:
$("#industry").on("change",function(){ var selectedId = $(this).find("option:selected").prop("id"); console.log(selectedId); });
内容的提问来源于stack exchange,提问作者Ajith Vinayak
相关产品推荐
相关产品推荐

