javascript 原型 - 如何从下拉列表中取消选择选定的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6414253/
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-25 20:34:52  来源:igfitidea点击:

Prototype - How to deselect the selected value from a dropdown

javascripthtmlprototypejs

提问by woot586

How do I deselect the selected value from a dropdown list using Prototype.

如何使用 Prototype 从下拉列表中取消选择选定的值。

From

<select id=“mylist” MULTIPLE >
<option value=“val-1”>Value 1</option>
<option value=“val-2” SELECTED>Value 2</option>
<option value=“val-3”>Value 3</option>
</select>

To

<select id=“mylist” MULTIPLE >
<option value=“val-1”>Value 1</option>
<option value=“val-2”>Value 2</option>
<option value=“val-3”>Value 3</option>
</select>

Thanks for any help in advance.

提前感谢您的任何帮助。

采纳答案by woot586

I found the following code worked well:

我发现以下代码运行良好:

var options = $$('select#mylist option');
var len = options.length;
for (var i = 0; i < len; i++) {
  options[i].selected = false;
}

回答by kzh

I'm not sure how to do it in prototype, but I can do it in JavaScript.

我不确定如何在原型中做到这一点,但我可以在 JavaScript 中做到这一点。

For a regular select, set yourSelectElement.selectedIndex = -1.

对于常规选择,设置yourSelectElement.selectedIndex = -1.

For a multiple select, you can just ctrl+clickon the selected item, but you can do it programmatically as well. See link.

对于多选,您可以只在所选项目上加ctrl+ click,但您也可以通过编程方式进行。见链接。

http://jsfiddle.net/kaleb/WxJ9R/

http://jsfiddle.net/kaleb/WxJ9R/

回答by remi bourgarel

You can't : you'll have to add an empty option

你不能:你必须添加一个空选项

<option></option> 

and then

接着

$$("#mylist option[selected]")[0].selected = false;
$$("#mylist option")[0].selected = true;

回答by clockworkgeek

On the event of the second list being selected...

在选择第二个列表的事件...

Event.observe('secondlist', 'change', function(){
  if (this.selectedIndex >= 0) 
    $$('#mylist option[selected]').invoke('writeAttribute', 'selected', false);
});