首页 > 解决方案 > 选择 Javascript 和 HTML 选项时如何更改图像

问题描述

我对选择选项时如何显示图片感到困惑。例如,我从 HTML 中的选项中选择 Spring,它应该从外部源 Javascript 链接。一张图片应该出现一张春天的图片。我确实尝试过使用 if 语句,如果 value = "Spring" 那么会出现一个图像。

    <html>
    <body>
        <img src="" name="changepic">
        <select name="allseasons" id="allseasons">
            <option value="Spring">Spring</option>
            <option value="Summer">Summer</option>
            <option value="Fall">Fall</option>
            <option value="Winter">Winter</option>
        </select>
    </body>
    </html>

Javascript

element=document.getElementById('allseasons');
if (value =="spring");
    element.src="spring.jpg"
if (value =="summer"); 
    element.src="summer.jpg"
if (value =="fall"); 
    element.src="fall.jpg"
if (value =="winter"); 
    element.src="winter.jpg"
} 

标签: javascripthtml

解决方案


  • 您应该将事件侦听器附加到<select>
  • 其次,您应该将 存储srcvalueof 中,<option>这样您就不需要检查每个src.
  • 不要放在语句;的末尾。if无论条件是真还是假,它都会始终运行它下面的代码
    const element = document.querySelector('#changepic');
    console.log(element);
    document.querySelector('#allseasons').addEventListener('change',(e) => {
      element.src = e.target.value;
      console.log(element);
    })
    <img src="" name="changepic" id="changepic">
        <select name="allseasons" id="allseasons">
            <option value="spring">Spring</option>
            <option value="summer">Summer</option>
            <option value="fall">Fall</option>
            <option value="winter">Winter</option>
        </select>

推荐阅读