根据选择选项

时间:2015-09-15 11:50:55

标签: javascript html html-select

我正在尝试根据下拉菜单中的所选选项显示div。它可以使用选项12,但是当我选择第二个选项时,它会显示第三个div

function valueNew(ele) {
  // get all div with class name 'div'
  var div = document.getElementsByClassName('div');
  // iterating over them and hidding all
  for( var i=0;i<div.length;i++) {
    div[i].style.display = 'none'
  }
  // getting div which is need to show using value of selected option
  div[ele.value].style.display = 'block';
}

// trigger change event to show default div
document.getElementById('sel').onchange();
<select id="sel" onChange="valueNew(this)">
  <option value="0">1</option>
  <option vlaue="1">2</option>
  <option value="2">3</option>
</select>

<div class="div" style="background:#ddd;width:100%; height:500px; display:none">1</div>
<div class="div" style="background:#ddd;width:100%; height:500px;display:none">2</div>
<div class="div" style="background:#ddd;width:100%; height:500px;display:none">3</div>

1 个答案:

答案 0 :(得分:3)

你有一个拼写错误:

package marcus_cory2;

import java.util.Random;

public class GamePlay {
        public static void main(String[] args) { 
                System.out.println(randomInteger(1,10));
        } 

        public static int randomInteger(int min, int max) { 
                Random rand = new Random();
                int randomNum = rand.nextInt((max - min) + 1) + min;
                return randomNum;


        } 
} 

更改为:

 <option vlaue="1">2</option>

看到它正常工作:

 <option value="1">2</option>
function valueNew(ele) {
  // get all div with class name 'div'
  var div = document.getElementsByClassName('div');
  // iterating over them and hidding all
  for( var i=0;i<div.length;i++) {
    div[i].style.display = 'none'
  }
  // getting div which is need to show using value of selected option
  div[ele.value].style.display = 'block';
}

// trigger change event to show default div
document.getElementById('sel').onchange();