获取for循环以忽略空值/空值

时间:2016-06-14 14:37:22

标签: javascript

我需要你的帮助,

如何修改下面的代码,以便我可以让我的for循环忽略空白/空值,这是用户在颜色选择框中可用的可选选项?

以下是相关代码:

<!DOCTYPE html>
<html>

<head>
  <script type="text/javascript">
    function test() {
      var x = document.getElementById("colors")
      for (var i = 0; i < x.length; i++) {
        alert(x.options[i].value)
      }
    }
  </script>
</head>

<body>
  <select id="colors">
    <option value=""></option>
    <option value="Red">Red</option>
    <option value="Blue">Blue</option>
    <option value="Green">Green</option>
    <option value="Yellow">Yellow</option>
    <option value="Orange">Orange</option>
  </select>
  <br>
  <br>
  <input type="button" value="test" onclick="test()">
</body>

</html>

2 个答案:

答案 0 :(得分:0)

您只需在for循环中设置i=1,而不是i=0

答案 1 :(得分:0)

您可以进行可用性检查:

if(value) alert(value)

示例

&#13;
&#13;
function test() {
  var x = document.getElementById("colors")
  for (var i = 0; i < x.length; i++) {
    if(x.options[i].value) alert(x.options[i].value)
  }
}
&#13;
<select id="colors">
  <option value=""></option>
  <option value="Red">Red</option>
  <option value="Blue">Blue</option>
  <option value="Green">Green</option>
  <option value="">Test</option>
  <option value="Yellow">Yellow</option>
  <option value="Orange">Orange</option>
</select>
<br>
<br>
<input type="button" value="test" onclick="test()">
&#13;
&#13;
&#13;