如何以这种简单的下拉形式更改(显示)图像?

时间:2019-01-22 13:08:23

标签: javascript

我要在“表单”下方为每个选定选项显示图像。

<form name="dropdown">
        <select name="selected" id="target" onchange="changeText()">
        <option value="nothing" selected>...Select...</option>
        <option value="http://www.google.com">Google</option>
        <option value="http://www.facebook.com/">Facebook</option>
        <option value="http://www.instagram.com/">Instagram</option>
        </select>
        <input type="button" value="Go There" id="butGo" onclick="goToNewPage()">
    </form>


function goToNewPage() {
    url = document.getElementById('target').value;
    //alert(url)
        if(document.getElementById('target').value!='nothing'){
            window.open(url,'_blank');
        }
    }

image1,image2,image3 ...

要在表格下方显示每个选定选项的图像! 谢谢!

1 个答案:

答案 0 :(得分:1)

经过测试,可以正常工作。希望对您有帮助!

function goToNewPage() {
    url = document.getElementById('target').value;
    //alert(url)
        if(document.getElementById('target').value!='nothing'){
            window.open(url,'_blank');
        }
    }
    
    
    function changeImage(){

  var e = document.getElementById("target");
  var selected = e.options[e.selectedIndex];
  var value = selected.value;
  var theimage = document.getElementById("theImage");
  if(value == "nothing"){
    theimage.style.display = "none";
  }else{
    theimage.style.display = "block";

  }
  var imgsrc = selected.getAttribute("data-image");

  theimage.src = imgsrc;

}
<form name="dropdown">
          <select name="selected" id="target" onchange="changeImage()">
          <option value="nothing" selected>...Select...</option>
          <option value="http://www.google.com" data-image="https://yt3.ggpht.com/a-/AAuE7mAOzJeUhnaCQpCrB8z58jvoroZFpAAB_9nD7w=s900-mo-c-c0xffffffff-rj-k-no">Google</option>
          <option value="http://www.facebook.com/" data-image="https://upload.wikimedia.org/wikipedia/commons/thumb/c/cd/Facebook_logo_%28square%29.png/600px-Facebook_logo_%28square%29.png">Facebook</option>
          <option value="http://www.instagram.com/" data-image="https://cdn.pixabay.com/photo/2016/09/17/07/03/instagram-1675670_960_720.png">Instagram</option>
          </select>
          <input type="button" value="Go There" id="butGo" onclick="goToNewPage()">
      </form>

      <img src="" id="theImage" style="display:none;max-width: 200px;margin-top:5%;" />