我需要获取select标签中所有选定选项的数据,为此我使用onclick()函数,该函数仅提供单击选项的数据.但是如果用户选择CTRL * A的所有选项,则不会收到任何数据.我试过使用在这种情况下不起作用的select().
//jQuery onclick()
$('select[name=sensors]').on('click', function(){
$('#demo').text($('select[name=sensors]').val());
});
//jQuery select()
$('select[name=sensors]').select(function(){
$('#demo2').text($('select[name=sensors]').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select type='list' name='sensors' multiple>
<option value= "e11">e11</option>
<option value= "e12">e12</option>
<option value= "e13">e13</option>
<option value= "e14">e14</option>
</select>
<!--jQuery onclick()-->
<div id="demo"></div>
<!--jQuery select()-->
<div id="demo2"></div>
解决方法:
不要在点击时绑定,而是在更改时绑定.这样,即使是来自其他类型的交互的更改也会被考虑在内:
$('select[name=sensors]').on('change', function(){
$('#demo').text($('select[name=sensors]').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select type='list' name='sensors' multiple>
<option value= "e11">e11</option>
<option value= "e12">e12</option>
<option value= "e13">e13</option>
<option value= "e14">e14</option>
</select>
<div id="demo"></div>
至于你对select的实验,这是the documentation所说的:
The select event is sent to an element when the user makes a text
selection inside it. This event is limited to
fields and boxes.
这里根本不相关,因为用户没有选择文本而是选项.