javascript 如果选择它,如何从单击多次选择中取消选择选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16697173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:40:16  来源:igfitidea点击:

How can I unselect an option from a multi select on a click ONLY if it is selected

javascriptjqueryhtml

提问by code511788465541441

I have a multi select element and once I select an option on it, is it then impossible to unselect all the options. I need to unselect the option when I click it and it was previously selected.

我有一个多选元素,一旦我选择了一个选项,就不可能取消选择所有选项。我需要在单击该选项时取消选择该选项,并且之前已选择该选项。

I have tried a few things but they don't work because everytime i click the option it becomes selected whether it was or not so its impossible to know if it was previously selected and should be unselected or if its the first time i am clicking it to select it

我尝试了一些东西,但它们不起作用,因为每次我单击该选项时,它都会被选中,无论它是否被选中,因此无法知道它之前是否被选中并且应该被取消选中,或者是我第一次点击它选择它

http://jsfiddle.net/JRgdv/

http://jsfiddle.net/JRgdv/

<select  multiple="multiple">
    <option>11111</option>
    <option selected>2</option>
    <option>33333</option>
    <option>44444</option>
</select>

I know I can have button or an area that i can click to clear the whole thing but i am truying to make it so that if you click a selected option then it unselects it

我知道我可以有按钮或一个区域,我可以点击它来清除整个内容,但我确实做到了,这样如果你点击一个选定的选项,它就会取消选择它

edit: CTRL+Click is not what i am looking for. it has to be with the mouse only

编辑:CTRL+Click 不是我要找的。它必须只用鼠标

回答by A. Wolff

Could be a workaround:

可能是一种解决方法:

SEE DEMO

看演示

$('select option').on('mousedown', function (e) {
    this.selected = !this.selected;
    e.preventDefault();
});

EDIT: this doesn't work on IE (version???). For cross browser solution, even uggly, try that instead: https://stackoverflow.com/a/21797607/1414562

编辑:这不适用于 IE(版本???)。对于跨浏览器解决方案,即使是丑陋的,也可以尝试:https://stackoverflow.com/a/21797607/1414562

回答by tymeJV

This may be a little hack-ish, but it works. Demo: http://jsfiddle.net/tymeJV/JRgdv/1/

这可能有点hack-ish,但它有效。演示:http: //jsfiddle.net/tymeJV/JRgdv/1/

var currentSelect = $("select option:selected").index();

$("select option").click(function() {
    if ($(this).index() == currentSelect) {
        $(this).prop("selected", false);
        currentSelect = -1;
    } else {
        currentSelect = $(this).index();
    }
});