首页 > 解决方案 > 如何在不按控制键的情况下从选择中获取多个选项?

问题描述

我的 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>

标签: javascriptjqueryhtmlthymeleaf

解决方案


select按 id选择第二个语句。处理mousedownmousemove事件:

$("#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());

推荐阅读