if..else ..用选择框值javascript和html

时间:2012-12-30 20:58:57

标签: javascript html

我有一个带有三个不同选项的选择框(4个实际上是空白的选项),点击一个按钮后我需要一个警告框来显示一条消息。这是一些代码。

HTML:

<select id="item1" name="Item 1">
      <option></option>
      <option value="1">Camera</option>
      <option value="2">Microphone</option>
      <option value="3">Tripod</option>
    </select>

    <button onclick="message()">Go!</button>

使用Javascript:

    <SCRIPT language = javascript>

function message() {

var s = document.getElementById('item1');
var item1 = s.options[s.selectedIndex].value;

if (item1 = 1) {
    alert("it equals camera")
}
else if (item1 = 2) {
    alert("it equals microphone")
}
else if (item1 = 3) {
    alert("it equals tripod")
}
}

</SCRIPT>

每次我点击按钮时,警告框都会显示“它等于相机”。我可以选择麦克风并单击按钮,它仍然会说。

如果我把

alert(item1)

在它显示1,2或3的函数中。所以我假设它是if..else ..语句。

5 个答案:

答案 0 :(得分:4)

在JavaScript中我们应该使用===,此也会检查数据类型

答案 1 :(得分:2)

请记住使用==代替=

if(item == 1)

而不是

if(item = 1)

答案 2 :(得分:1)

替换

if (item1 = 1) {

if (item1 == 1) {

(和其他人一样)

item = 1更改item1的值并返回1,其在测试中评估为true

但请注意,您可以更有效率地

  • 使用开关
  • 或直接读取值

例如:

document.getElementById('item1').onchange = function(){
    alert("it equals " + this.options[this.selectedIndex].innerHTML);        
}​​​​​​​​

Demonstration

答案 3 :(得分:1)

在JavaScript(几乎所有其他大括号语言)中,单=始终意味着分配。因此,您将值1分配给item1

您需要比较运算符==

function message() {
    var s = document.getElementById('item1');
    var item1 = s.options[s.selectedIndex].value;

    if(item1 == '1') {
        alert("it equals camera")
    } else if(item1 == '2') {
        alert("it equals microphone")
    } else if(item1 == '3') {
        alert("it equals tripod")
    }
}

以下是一些改进代码的其他建议:

  • 请勿使用language的已弃用的<script>属性。如果您想要明确,只需<script>适用于JavaScript或<script type="text/javascript>
  • 不要使用内联事件。而不是onclick="..."使用addEventListener()方法注册事件处理程序。

答案 4 :(得分:0)

为什么不使用这种方法,当你的选择器获得更多项目时会更容易?

var s = document.getElementById("item1");
var item1 = s.options[s.selectedIndex].text;
window.alert('it equals '+item1);

修改: JSFiddle

修改2 :将=更改为==可解决您的问题。而不是使用s.options[s.selectedIndex].value,您只需使用s.selectedIndex即可。这也将返回1,2或3,这更容易理解。