javascript - 如何在不按控制键的情况下从选择中获取多个选项?
问题描述
我的 html 代码中有 2 个“选择”,从第一次选择开始,我只想选择一个选项,从第二次选择开始,我想选择多个选项。我在 jquery 中编写了代码以从 select 中获取多个选项。
jQuery
$('option').mousedown(function(e) {
e.preventDefault();
$(this).prop('selected', !$(this).prop('selected'));
return false;
});
这段代码运行良好,但问题是我的第二次选择运行良好,但在我的第一次选择中我无法选择任何选项,我只想从第一次选择中获得一个选项。
HTML
<div class="form-group">
<div class="col-sm-3">
<label style="width: 100%;" class="control-label"
th:text="#{CLONE.MASTERID}"></label>
</div>
<div class="col-sm-9">
<select class="form-control" id="cloneMasterIds">
<option value="">Select Master Device Id</option>
<option th:each="master : ${masterIds}" th:value="${master.value}"
th:utext="${master.value}">Wireframe</option>
</select>
<p class="field-error hidden-true"
id="SerialNumber-Error" th:text="#{ERROR.CLONE.MASTERID}"></p>
</div>
</div>
<!-- Child IDs -->
<div class="form-group">
<div class="col-sm-3">
<label style="width: 100%;" class="control-label"
th:text="#{CLONE.CHILDID}"></label>
</div>
<div class="col-sm-9">
<select class="form-control select-checkbox" id="cloneChildIds"
multiple="multiple">
<option th:each="child : ${childIds}" th:value="${child.value}"
th:utext="${child.value}">Wireframe</option>
</select>
<p class="field-error hidden-true"
id="SerialNumber-Error" th:text="#{ERROR.CLONE.CHILDID}"></p>
</div>
</div>
解决方案
select
按 id选择第二个语句。处理mousedown
和mousemove
事件:
$("#cloneChildIds").mousedown(function(e){
e.preventDefault();
var select = this;
var scroll = select.scrollTop;
e.target.selected = !e.target.selected;
setTimeout(() => select.scrollTop = scroll, 0);
$(select).focus();
}).mousemove(e => e.preventDefault());
推荐阅读
- android - 我需要从回调方法内部获取值的返回
- multithreading - 在烧瓶应用程序中使用 requests_html
- database - 在 MongoDB 中使用 $pull 更新文档的内部数组
- java - 如何使用 Spring Data 将异步插入 Cassandra?
- java - 如何在 Java 中使用 GraphQL?
- c# - 部署到 azure webapps 后,引导下拉菜单不起作用
- ruby-on-rails - Rails4 mysql表关于多态
- android - 使用 CipherInputStream 解密文件
- java - 尝试 Catch 不起作用 - 为什么?
- php - 如何在 WordPress 上获取帖子的自定义文件?