MooTools - 如何使用 getSelected()

2024-02-21

我正在努力学习 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 上关于此方法的文档是 SPARSE 并且只说:

元素方法:getSelected

返回选定的选项 选择元素。

Returns:

* (array) An array of the selected elements.

例子: 超文本标记语言

<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.

Note:

无论 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") or $("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/ http://www.jsfiddle.net/dimitar/SmShF/

玩得开心并阅读手册:)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MooTools - 如何使用 getSelected() 的相关文章

随机推荐