javascript – jQuery select()方法不起作用

我需要获取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.

这里根本不相关,因为用户没有选择文本而是选项.

相关文章

1.第一步 设置响应头 header(&#39;Access-Control-Allow...
$.inArray()方法介绍 $.inArray()函数用于在数组中搜索指定的...
jquery.serializejson.min.js的妙用 关于这个jquery.seriali...
JS 将form表单数据快速转化为object对象(json对象) jaymou...
jQuery插件之jquery.spinner数字智能增减插件 参考地址:http...