这个for循环在javascript中有什么问题?

时间:2016-02-24 14:03:47

标签: javascript html

我想用javascript在html中制作简单的选项,我有以下代码:

<script type="text/javascript">
var capitals = {
California : "Los Angeles",
Georgia : "Atlanta",
Florida : "Miami"
}
window.onload = function() {
var mySelect = document.getElementById("states")
for ( state in capitals) {
    var myOption = document.createElement("option")
    myOption.text = state;
    myOption.value = state;
    mySelect.appendChild(myOption)
}
mySelect.onchange = function(){
if (this.value != ""){
alert("The capital of" + this.value + " is " capital[this.value]);

}

}
}

</script>

这是html代码:

<select id="states">
         <option value=""> Select state </option>
    </select>

但它不起作用:(

3 个答案:

答案 0 :(得分:1)

你在onchange块中有语法错误

&#13;
&#13;
var capitals = {
California : "Los Angeles",
Georgia : "Atlanta",
Florida : "Miami"
}

var mySelect = document.getElementById("states")
for ( state in capitals) {
    var myOption = document.createElement("option")
    myOption.text = state;
    myOption.value = state;
    mySelect.appendChild(myOption)
}
mySelect.onchange = function(){
if (this.value != ""){
alert("The capital of" + this.value + " is " +  capital[this.value]);

}

}
&#13;
<select id="states">
         <option value=""> Select state </option>
    </select>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

JavaScript控制台是一款可以为您节省大量时间的工具。点击Chrome中的F12,Windows上的Firefox或IE将打开一个面板,您可以在其中访问错误日志,网络请求等数据。

如果您导航到Console标签,则会在警报中看到错过+个签名,并且在{{1}之后忘记了s在同一条线上。

capital

应该是

alert("The capital of " + this.value + " is " capital[this.value]);

试一试

&#13;
&#13;
alert("The capital of" + this.value + " is " + capitals[this.value]);
&#13;
var capitals = {
  California: "Los Angeles",
  Georgia: "Atlanta",
  Florida: "Miami"
};
window.onload = function() {
  var mySelect = document.getElementById("states");
  for (state in capitals) {
    var myOption = document.createElement("option");
    myOption.text = state;
    myOption.value = state;
    mySelect.appendChild(myOption);
  }
  mySelect.onchange = function() {
    if (this.value != "") {
      alert("The capital of " + this.value + " is " + capitals[this.value]);
    }
  };
}
&#13;
&#13;
&#13;

答案 2 :(得分:0)

你有很多小错误:

var capitals = { //keys need to be in quotes
    "California" : "Los Angeles",
    "Georgia" : "Atlanta",
    "Florida" : "Miami"
};

window.onload = function() {
    var mySelect = document.getElementById("states");
    
    for (var state in capitals) { //add var
        var myOption = document.createElement("option");
        myOption.text = state;
        myOption.value = state;
        mySelect.appendChild(myOption);
    }
    mySelect.onchange = function(){
        if (this.value != ""){
            alert("The capital of" + this.value + " is " + capitals[this.value]); //add "+" and make it "capitals"
        }
    }
}
<select id="states">
    <option value=""> Select state </option>
</select>