我正在尝试添加选项以使用JavaScript动态地为大学作业选择元素。
我们正在为健身房创建班级预订系统,以便用户可以预订班级。我想使用下拉框,因此您要选择班级,然后使用下一个下拉框来选择时间,因此必须根据所选的班级进行更改。最后,用户将在最后一个框中选择私人教练,然后根据选择的时隙再次创建该私人教练。
到目前为止,这是我所拥有的(javascript方面):
<script type="text/javascript">
function getTimes()
{
var index=document.getElementById("classes").selectedIndex;
var x=document.getElementById("schedule");
if(index==0)
{
document.getElementById("schedule").value=" ";
}
else if(index==1)
{
var option=document.createElement("option");
option.text="Monday 8:00pm";
try
{
// for IE earlier than version 8- from w3 schools
x.add(option,x.options[null]);
}
catch (e)
{
x.add(option,null);
}
}
}
和html:
<div>
<span class="label">Class:</span>
<select class="dropdown" id="classes" name="classes" onChange="getTimes();">
<option value="none"> </option>
<option value="pilates">Pilates</option>
<option value="crossfit">Cross Fit</option>
</select>
</div>
<div>
<span class="label">Time:</span>
<select class="dropdown" id="schedule"></select>
</div>
<div>
<span class="label">Trainer:</span>
<select class="dropdown" id="trainer"></select>
</div>
对于代码来说,它似乎应该可以工作,但是无论出于什么原因,当我选择第一个类时,在这种情况下,“普拉提”中的“时间”下拉框仍为空白。
谁能告诉我我要去哪里错了?
错误在函数的第一行
function getTimes();
^------ You have a semi colon here
which is not supposed to be there
如果再次引用相同的元素,则最好是缓存选择器。使用Javascript绑定事件,而不是内联绑定。
// Store you selectors so that you can use later
// This will improve your performance
var classDropdown = document.getElementById("classes"),
scheduleDropdown = document.getElementById("schedule");
// Abbd events using javascript
classDropdown.addEventListener('change', getTimes);
function getTimes() {
var index = classDropdown.selectedIndex;
if (index == 0) {
scheduleDropdown.value = " ";
} else if(index == 1) {
var option = document.createElement("option");
option.text = "Monday 8:00pm";
try {
// for IE earlier than version 8- from w3 schools
scheduleDropdown.add(option, x.options[null]);
} catch (e) {
scheduleDropdown.add(option, null);
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句