简体   繁体   English

jQuery / JavaScript-根据选择选项在另一个div中更改图像

[英]jQuery / JavaScript - Change image in another div based on select option

I have created a select option: 我创建了一个选择选项:

<select>
    <option value="samsung">Samsung</option>
    <option value="apple">Apple</option>
    <option value="lg">LG</option>
    <option value="htc">HTC</option>
</select>

Later in the code, I have: 在代码的后面,我有:

<div class="col-lg-6 text-center"> <!-- bootstrap stuff -->
    <img id="changePictureYo" src="Slike/uredjajS1.png"/>
</div>

I want the img src to change depending on the selected option. 我希望img src根据所选选项进行更改。 (So if I select Apple, the img src would change to Slike/iphone.png). (因此,如果我选择Apple,则img src将更改为Slike / iphone.png)。
I have tried this: 我已经试过了:

<select>
    <option value="samsung">Samsung</option>
    <option value="apple" onselect="changeImage()">Apple</option>
    <option value="lg">LG</option>
    <option value="htc">HTC</option>
</select>

And in my .js file: 在我的.js文件中:

function changeImage() {
    document.getElementById("changePictureYo").src = "Slike/iphone.png";
}

But it is not working. 但这是行不通的。 What am I missing? 我想念什么?

The event onSelect is not supported by the <option> tag <option>标签不支持onSelect事件

The select event only fires when text inside a text input or textarea is selected. 仅当选择了文本输入或文本区域内的文本时,才会触发select事件。 The event is fired after the text has been selected. 选择文本后将触发该事件。

You need to use onChange event. 您需要使用onChange事件。

<select onchange="changeImage(this)">
  <option value="samsung">Samsung</option>
  <option value="apple">Apple</option>
  <option value="lg">LG</option>
  <option value="htc">HTC</option>
</select>

JS : JS:

function changeImage(el) {
  if (el.value == "apple") {
    document.getElementById("changePictureYo").src = "Slike/iphone.png";
  }
}

Try this 尝试这个

<select id="img_change">
<option value="samsung">Samsung</option>
<option value="iphone">Apple</option>
<option value="lg">LG</option>
<option value="htc">HTC</option>

<div class="col-lg-6 text-center"> <!-- bootstrap stuff -->
<img id="changePictureYo" src=""/>

** jQuery code ** ** jQuery代码**

jQuery(document).ready(function($){

$('#img_change').on('change', function(){

        var img_path = 'someDir/' + $(this).val() + '.jpg';
        $('#changePictureYo').attr( 'src', img_path );
});

}); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM