在JavaScript中切换并选择

在JavaScript中切换并选择,javascript,html,select,switch-statement,Javascript,Html,Select,Switch Statement,我是JavaScript新手。。这是我的问题。。我有下拉列表: <div class="spanNav-row" id="spanNav-row"> <select name="timeDropList"> <option value="6">6</option> <option value="10">10</option> <option value="15">15</opt

我是JavaScript新手。。这是我的问题。。我有下拉列表:

<div class="spanNav-row" id="spanNav-row">
  <select name="timeDropList">

    <option value="6">6</option>
    <option value="10">10</option>
    <option value="15">15</option>
    <option value="30">30</option>
    <option value="60" selected>60</option>
    <option value="Vac">Vacation</option>

  </select>
</div>
如何将下拉列表的值传输到交换机

var swi_var = document.getElementById('spanNav-row').value;
swi_var
可以进入开关

swi_var
可以进入开关

标准JS:

var ddl = document.getElementById("timeDropList");
var selectedValue = ddl.options[ddl.selectedIndex].value;

switch (selectedValue) {}
jQuery(如果您感兴趣):

注意:要通过getElementById()引用下拉列表,timeDropList还必须是ID,而不仅仅是名称:

<select id="timeDropList" name="timeDropList">

标准JS:

var ddl = document.getElementById("timeDropList");
var selectedValue = ddl.options[ddl.selectedIndex].value;

switch (selectedValue) {}
jQuery(如果您感兴趣):

注意:要通过getElementById()引用下拉列表,timeDropList还必须是ID,而不仅仅是名称:

<select id="timeDropList" name="timeDropList">

如果您使用jQuery,它将是小菜一碟:

var selectedValue = $('#spanNav-row').val();
switch (selectedValue) {
    // Your switch body here.
}

如果您使用jQuery,它将是小菜一碟:

var selectedValue = $('#spanNav-row').val();
switch (selectedValue) {
    // Your switch body here.
}

好吧。。您能否解释一下为什么使用getElementsById(“spanNav行”)而不是“TimedLopList”?这会引发一个错误,因为HtmlLevel上不存在
options
HTMLCollection。我建议将
id
属性附加到select,然后对其值进行切换。@Sergio,抱歉,已更新。我把这归咎于小小的上网本屏幕。我复制并粘贴了错误的id…@James Hill-别担心,其他人也弄错了。:)我唯一要注意的是它是一个
名称
值,而不是
id
值…@Jared Farrish,在看到你的评论之前,我刚刚在我的帖子中更新了它。说真的,9英寸的屏幕快把我累死了:)好的..你能解释一下为什么你用getElementsById(“spanNav row”)而不是“timeDropList”吗“?这会引发一个错误,因为HtmlLevel上不存在
options
HTMLCollection。我建议将
id
属性附加到select,然后对其值进行切换。@Sergio,抱歉,已更新。我把这归咎于小小的上网本屏幕。我复制并粘贴了错误的id…@James Hill-别担心,其他人也弄错了。:)我唯一要注意的是它是一个
名称
值,而不是
id
值…@Jared Farrish,在看到你的评论之前,我刚刚在我的帖子中更新了它。说真的,9英寸的屏幕快把我累死了:)你可以用JavaScript做同样的事情,而不用jQuery膨胀:
document.getElementById(“id\u of\u select”).value;
。是的,我同意@Matt。但是真正的应用程序超出了这一点。那么为什么不合并jQuery呢?jQuery很好,但在本例中OP没有提到它,而且有一个非常简单的答案不需要它……你可以用JavaScript做完全相同的事情,而不需要jQuery膨胀:
document.getElementById(“id_of_select“).value;
。是的,我同意@Matt。但真正的应用程序远远不止于此。那么为什么不合并jQuery呢?jQuery很好,但在这个例子中,OP没有提到它,而且有一个非常简单的答案,不需要它……演示:你需要打开Chrome控制台或Firefox Firebug控制台来查看输出。演示:你将需要打开Chrome控制台或Firefox Firebug控制台才能查看输出。