如何设置要从下拉菜单选项中显示的图像?

时间:2022-11-19 23:26:10

I'm trying to make a form that displays a movie poster when you select which movie you'd like to see. I wrote a function but I'm new to javascript and something isn't working correctly.

当您选择要观看的电影时,我正在尝试制作一个显示电影海报的表单。我写了一个函数,但我是javascript的新手,有些东西工作不正常。

Thanks for any help provided.

感谢您提供的任何帮助。

JS

function setMovie() {
  var img = document.getElementById("movimg");
  var value = img.options[img.selectedIndex].value;
  var selected = document.getElementById("selectedMovie");
  selected.src = this.value;
  return false;
}
document.getElementById("movieList").onChange = setMovie();

HTML

<select id="movimg" onChange="setMovie(this)">
  <option value="null.png">Select a movie!</option>
  <option value="bvs.jpg">Batman vs. Superman</option>
  <option value="tjb.jpg">The Jungle Book</option>
  <option value="tgf.jpg">The Godfather</option>
  <option value="tpb.jpg">The Princess Bride</option>
  <br>
</select>
<img src="" id="selectedMovie" />

2 个解决方案

#1


0  

You were referencing movieList, an id that wasn't there. You also did not need to return false in your function.

你正在引用movieList,一个不存在的id。您也不需要在函数中返回false。

var select_box = document.getElementById("movimg"),
    image_box = document.getElementById("selectedMovie");

function setMovie() {
  var value = select_box.options[select_box.selectedIndex].value;
  image_box.src = this.value;
}

select_box.addEventListener("change", setMovie);
<select id="movimg">
        <option value="null.png">Select a movie!</option>
        <option value="bvs.jpg">Batman vs. Superman</option>
        <option value="tjb.jpg">The Jungle Book</option>
        <option value="tgf.jpg">The Godfather</option>
        <option value="tpb.jpg">The Princess Bride</option>
</select> 
<img src="" id="selectedMovie"/>

#2


0  

You can just change your function to this:

您可以将功能更改为:

 function setMovie(){
    document.getElementById("selectedMovie").src = document.getElementById("movimg").value;
    }

#1


0  

You were referencing movieList, an id that wasn't there. You also did not need to return false in your function.

你正在引用movieList,一个不存在的id。您也不需要在函数中返回false。

var select_box = document.getElementById("movimg"),
    image_box = document.getElementById("selectedMovie");

function setMovie() {
  var value = select_box.options[select_box.selectedIndex].value;
  image_box.src = this.value;
}

select_box.addEventListener("change", setMovie);
<select id="movimg">
        <option value="null.png">Select a movie!</option>
        <option value="bvs.jpg">Batman vs. Superman</option>
        <option value="tjb.jpg">The Jungle Book</option>
        <option value="tgf.jpg">The Godfather</option>
        <option value="tpb.jpg">The Princess Bride</option>
</select> 
<img src="" id="selectedMovie"/>

#2


0  

You can just change your function to this:

您可以将功能更改为:

 function setMovie(){
    document.getElementById("selectedMovie").src = document.getElementById("movimg").value;
    }