我正在努力学习 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/