JavaScript 代码块中的“选项”来自哪里?
where does ''options" come from in this JavaScript block of code?
i have this code from MDN which i am trying to understand !
第一:>
“options”在这个块中来自哪里:-
for (var i = 0; i < selectObject.options.length; i++) {
if (selectObject.options[i].selected)
*
秒:>
why it 'options' does work fine inside the function and not work outside the function
这是代码-
<form name="selectForm">
<p>
<label for="musicTypes">Choose some music types, then click the button below:</label>
<select id="musicTypes" name="musicTypes" multiple="multiple">
<option selected="selected">R&B</option>
<option>Jazz</option>
<option>Blues</option>
<option>New Age</option>
<option>Classical</option>
<option>Opera</option>
</select>
</p>
<p><input id="btn" type="button" value="How many are selected?" /></p>
</form>
<script>
function howMany(selectObject) {
var numberSelected = 0;
for (var i = 0; i < selectObject.options.length; i++) {
if (selectObject.options[i].selected) {
numberSelected++;
}
}
return numberSelected;
}
var btn = document.getElementById('btn');
btn.addEventListener('click', function() {
alert('Number of options selected: ' + howMany(document.selectForm.musicTypes));
});
</script>
1) options
是 HTML DOM 的一部分,负责 selecting options
指定 select
元素内的元素
2) 它确实在任何 select 元素的函数之外工作,但我假设您正在尝试在函数之外使用 selectObject
,这违反了变量范围。
阅读更多:
i have this code from MDN which i am trying to understand !
第一:>
“options”在这个块中来自哪里:-
for (var i = 0; i < selectObject.options.length; i++) {
if (selectObject.options[i].selected)
*
秒:>
why it 'options' does work fine inside the function and not work outside the function
这是代码-
<form name="selectForm">
<p>
<label for="musicTypes">Choose some music types, then click the button below:</label>
<select id="musicTypes" name="musicTypes" multiple="multiple">
<option selected="selected">R&B</option>
<option>Jazz</option>
<option>Blues</option>
<option>New Age</option>
<option>Classical</option>
<option>Opera</option>
</select>
</p>
<p><input id="btn" type="button" value="How many are selected?" /></p>
</form>
<script>
function howMany(selectObject) {
var numberSelected = 0;
for (var i = 0; i < selectObject.options.length; i++) {
if (selectObject.options[i].selected) {
numberSelected++;
}
}
return numberSelected;
}
var btn = document.getElementById('btn');
btn.addEventListener('click', function() {
alert('Number of options selected: ' + howMany(document.selectForm.musicTypes));
});
</script>
1) options
是 HTML DOM 的一部分,负责 selecting options
指定 select
元素内的元素
2) 它确实在任何 select 元素的函数之外工作,但我假设您正在尝试在函数之外使用 selectObject
,这违反了变量范围。
阅读更多: