21

我有以下 HTML

<form>
  <div class="answer1wrap">
    <select id="mySelect">
      <option value="void">Choose your answer</option>
      <option value="To measure time">To measure time</option>
      <option value="To measure distance">To measure distance</option>
      <option value="To measure volume">To measure volume</option>
    </select>
  </div>
</form>

<button class="btn btn-default" id="checkbtn" onclick="answers();" type="button"><span    class="glyphicon glyphicon-check"></span> Check answers</button>

我也有 javascript

function answers()
{
  var selectedanswer=document.getElementById("mySelect").selectedIndex;

  if (document.getElementsByTagName("option")[selectedanswer].value=="To measure time");{
    alert("Thats correct"); 
  }
}

我希望当按下按钮时,它会检查是否选择了“测量时间”选项并仅在选择时提醒我。但是,无论选择了哪个选项,它总是显示警报。

有任何想法吗?

4

4 回答 4

21

也许这是您的if条件中的逗号。

function answers() {
var answer=document.getElementById("mySelect");
 if(answer[answer.selectedIndex].value == "To measure time.") {
  alert("That's correct!"); 
 }
}

你也可以这样写。

function answers(){
 document.getElementById("mySelect").value!="To measure time."||(alert('That's correct!'))
}
于 2013-09-17T10:10:31.813 回答
5

尝试

var e = document.getElementById("mySelect");
var selectedOp = e.options[e.selectedIndex].text;
于 2013-09-17T10:11:37.497 回答
5

我注意到的第一件事是你的 if 语句的右括号后面有一个分号);

您还应该尝试通过单独为答案声明一个变量来清理您的 if 语句。

function answers() {

var select = document.getElementById("mySelect");
var answer = select.options[select.selectedIndex].value;

    if(answer == "To measure time"){
        alert("Thats correct"); 
    }

}

http://jsfiddle.net/zpdEp/

于 2013-09-17T10:13:45.143 回答
3

工作 jsbin:http: //jsbin.com/ANAYeDU/4/edit

主要位:

function answers()
{

var element = document.getElementById("mySelect");
var elementValue = element.value;

if(elementValue == "To measure time"){
  alert("Thats correct"); 
  }
}
于 2013-09-17T10:12:42.290 回答