HTML - selectedindexchanged下拉列表第二次无法正常工作

时间:2015-04-12 10:57:29

标签: javascript html

以下是在更改下拉列表的值时应显示图像的代码 -

<html>
 <head><title>Image Display</title></head>
   <script type = "text/JavaScript">
        function displayImage() {
        var dropdown1 = document.getElementById('dropdown1');
        var index = dropdown1.options[dropdown1.selectedIndex].value;
    //alert(index);

    var img = new Image();  
    if(index == 0){
        img.src = "D:\\Images\\LamborghiniLaunche.png"
        imgDiv.appendChild(img);
    }   
    else if(index == 1){
        img.src = "D:\\Images\\Nano.JPG"
        imgDiv.appendChild(img);
    }
    else if(index == 2){
        img.src = "D:\\Images\\bmw-i8.jpg"
        imgDiv.appendChild(img);
     }
  }
  </script>
  <body>
<select id="dropdown1" name ="select" onchange="displayImage();">
    <option selected disabled>Select here</option>
    <option value ="0">Lamborghini Launche
    <option value ="1">Nano
    <option value ="2">BMW i8
    </option>
    </select>

<div id="imgDiv"></div>
</body>
</html>

问题: 在第一次选择下拉列表后,它会成功加载相应的图像,但第二次更改下拉值无法加载相应的图像。

1 个答案:

答案 0 :(得分:3)

您可能不想在每次选项更改时创建和添加新图片。可能是因为你的风格,你根本看不到新的形象,因为它是在第一个之后。

相反,如果图像不存在则创建图像,如果图像已经存在则更改其src。像这样:

&#13;
&#13;
function displayImage() {
    var dropdown1 = document.getElementById('dropdown1');
    var index = dropdown1.options[dropdown1.selectedIndex].value;

    var imgDiv = document.querySelector('#imgDiv img');
    if (!imgDiv) {
        imgDiv = new Image();
        document.querySelector('#imgDiv').appendChild(imgDiv);
    }
    
    if (index == 0) {
        imgDiv.src = "http://lorempixel.com/100/100/food/1";
    } else if (index == 1) {
        imgDiv.src = "http://lorempixel.com/100/100/food/2"
    } else if (index == 2) {
        imgDiv.src = "http://lorempixel.com/100/100/food/3";
    }
}
&#13;
<select id="dropdown1" name="select" onchange="displayImage();">
    <option selected disabled>Select here</option>
    <option value="0">Lamborghini Launche</option>
    <option value="1">Nano</option>
    <option value="2">BMW i8</option>
</select>
<div id="imgDiv"></div>
&#13;
&#13;
&#13;