欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

select第一个option选项选不中怎么回事_html/css_WEB-ITnose

程序员文章站 2022-05-17 21:52:43
...






$('#user_type').on('change', function(e) {
console.log(e.currentTarget.value);
var index = e.currentTarget.options.selectedIndex;
_eleTypeCode = e.currentTarget.value;
var text = e.currentTarget.options[index].text;
$("#user").val(text);
});


回复讨论(解决方案)

有没有人么啊

change事件是在选项改变时才会触发,页面加载后默认就是第一项被选中,这时你点了第一项,选项并没有改变,事件就不会被触发
可以在页面加载后让它没有选项被选中
$('#user_type')[0].selectedIndex = -1;
$('#user_type').on('change', function(e) {
console.log(e.currentTarget.value);
var index = e.currentTarget.options.selectedIndex;
_eleTypeCode = e.currentTarget.value;
var text = e.currentTarget.options[index].text;
$("#user").val(text);
});

实测可以选中任意一项, 但页面初始化时, 不会触发 onchange 事件, 所以也不会把 user 输入框的文本自动设置为第一项的值

3楼4楼说的对,加了$('#user_type')[0].selectedIndex = -1;果然可以选了