繁体   English   中英

使用javascript时,如何使用select表单来执行if else语句?

[英]when using javascript how do you use select form to do if else statements?

您如何以选择形式获取选项的值并将其用于if else语句?

例如,如果选择苹果作为选项,则向文档写入如何制作苹果酱,但是选择橙色,然后写入如何制作橙色?

到目前为止,我有一个基本的表单和选择选项,我知道如何做document.write,但是我不知道如何与其他情况一起使用选择表单

谢谢您的帮助

首先,请确保您在<select>上具有一个id ,以便您可以从Javascript中引用它:

<select id="fruits">...</select>

现在,您可以使用<select>的Javascript表示形式的optionsselectedIndex字段来访问当前选定的值:

var fruits = document.getElementById("fruits");
var selection = fruits.options[fruits.selectedIndex].value;

if (selection == "apple") {
    alert("APPLE!!!");
}

您的HTML标记

<select id="Dropdown" >
    <option value="Apple">Apple</option>
    <option value="Orange">Orange</option>
</select>

您的JavaScript逻辑

if(document.getElementById('Dropdown').options[document.getElementById('Dropdown').selectedIndex].value == "Apple") {
//write applesauce
}
else {
//everything else
}
var select = document.getElementById('myList');
if (select.value === 'apple') {
  /* Applesauce */
} else if (select.value === 'orange') {
  /* Orange */
}

或者,您可以执行此操作。

var fruitSelection = document.formName.optionName; /* if select has been given an name AND a form have been given a name */
/* or */ 
var fruitSelection = document.getElementById("fruitOption"); /* If <select> has been given an id */

var selectedFruit = fruitSelection.options[fruitSelection.selectedIndex].value;

if (selectedFruit == "Apple") {
  document.write("This is how to make apple sauce....<br />...");
} else {

}

// HTML

<!-- For the 1st option mentioned above -->

<form name="formName">
  <select name="optionName> <!-- OR -->
  <select id="optionName">
    <option value="Apple">Apple</option>
    <option value="Pear">Pear</option>
    <option value="Peach">Peach</option>
  </select>
</form>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM