html - MooTools - 如何使用 getSelected()

标签 html html-select mootools forms

我正在努力学习 MooTools,我是一个彻头彻尾的 javascript 菜鸟,所以请对我温柔一点。

我要做的是在选择特定选项时更改禁用输入字段(类型为文本)的状态。 html 看起来有点像:

<select class="wide" id="selectBox" name="option> 
  <optgroup label="Common">
      <option value="one">One<option>
      <option value="two">Two<option>
      <option value="three">Three<option>
  </optgroup>
  <optgroup label="Less Common">
      <option value="other">Other<option>
  </optgroup>
</select>
<input id="other" type="text" disabled="disabled" />

这就是我希望能给我在 if 语句中检查的值,然后将输入禁用更改为启用:

window.addEvent('domready', function(){
 $$('#selectBox').addEvent('change',function(){
  var selection = $$('#selectBox').getSelected();
  alert(selection);
   });
});

当我们运行代码时(即我在选项框中选择另一个值),我得到的只是[object HTMLOptionElement]

关于此方法的 mootools 文档是稀疏的,只说:

Element Method: getSelected

Returns the selected options of a select element.

Returns:

* (array) An array of the selected elements.

例子: HTML

<select id="country-select" name="country">
    <option value="US">United States</option
    <option value ="IT">Italy</option>
</select>

JavaScript

$('country-select').getSelected(); //Returns whatever the user selected.

注意:

这个方法返回一个数组,不管select元素的multiple属性如何。如果选择是单一的,它将返回一个只有一个项目的数组。

完全困惑!

有人请告诉我我错过了什么。我也试过:

var selection = $$('#selectBox').getSelected().value; //and
var selection = $$('#selectBox').getSelected('value'); //and
//a WHOLE bunch of other wild ideas including
var selection = $$('#selectBox').getSelected();
alert(selection[0]);

没有什么是正确的。在某些情况下,我得到 undefined,在其他情况下,我得到相同的 [object HTMLOptionElement]

最佳答案

很多事情都错了,不知道从哪里开始。

$$() 是一个集合运算符(document.getElements() 的别名,它根据选择器返回倍数)- 不适合用于 id。

你想要 document.id("idhere")$("idhere")

适用于 mootools 1.2+

document.id('selectBox').addEvent('change',function() {
    alert(this.get("value")); // get value
    alert(this.getSelected().get("value")); // gets the option that's selected and then it's value
});

确保你检查了你的标记 - 你没有关闭选项,你也从 name="option> 中丢失了 "。

getSelected 作为一种方法存在,因为某些选择使用多项选择,因此执行 selectEl.get("value") 不会报告任何有意义的内容。任何其他情况,.get("value") 都可以。

检查它是否正常工作: http://www.jsfiddle.net/dimitar/SmShF/

玩得开心并阅读手册:)

关于html - MooTools - 如何使用 getSelected(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3340459/

相关文章:

javascript - Dojo 数据网格 : set conditionally editable column (change at runtime)

css - <SELECT> 如果 Chrome 中的宽度较小,则将文本换行到下一行

javascript - 模板中默认选择 Angular 4 选项

javascript - MooTools if/then/else 切换基于 css 类的存在

javascript - 设置默认元素以显示 onload - mootools

html - 使用变换 : scale 防止模糊渲染

JavaScript 错误,战舰游戏

html - CSS:如何选择 ol 标签中包含的所有 ul 标签

javascript - 选择列表为空时水平缩小

javascript - Firefox 4 新点击事件行为的问题