JavaScript代码更改组合框输出中的所有图像,而不是所需的图像

JavaScript code changes all image instead of desired image on combobox output

本文关键字:图像 代码 组合 输出 JavaScript      更新时间:2023-09-26

我的代码按照我希望的方式工作,如中所示,当从组合框中选择某个值时,图像将更改为正确的图像。然而,我想改变的不仅仅是图像。这是我在html页面上的所有图像(徽标、小部件图像等)。我不想发生这种事,但只想得到我想要的形象。这是我的代码:

html:

<form name="animals">
<select id="imagecb">
    <option value="option1" selected>Please select... </option>
    <option value="option2">cat</option>
    <option value="option3">dog</option>
    <option value="option4">bird</option>
    <option value="option5">hamster</option>
</select><br />
</form>
<!-- This is the desired image to change via the selected option in the selectbox -->
<img src="(url)cat.png" /> 

javascript:

<script>
jQuery( function ($) { 
var pictureList = [
    "(url)cat.png",
    "(url)dog.png",
    "(url)bird.png",
    "(url)hampster.png" 
    ];
$('#imagecb').change(function () {
    var index = $(this).find( ':selected' ).index();
    $('img').attr( "src", pictureList[index] );
});
});
</script>

如果有人能帮忙那就太好了。

如果使用此
$('img').attr( "src", pictureList[index] );

它将更改您页面上的所有图像。

尝试在那些要更改的图像标记上添加一个类。喜欢
<img class="change_image" ..... </img>

现在更改javascript
$('.change_image').attr( "src", pictureList[index] );

您需要正确识别目标图像。

$('img').attr( "src", pictureList[index] );

img选择器以页面上的所有<img>元素为目标。改为使用id

<img id="targetImage" src="(url)cat.png" /> 
$('#targetImage').attr( "src", pictureList[index] );

您必须有一种方法来识别要更改的图像。例如,添加一个id属性:

<img src="(url)cat.png" id="myImage /> 

然后,在更改src标记时使用此id:

$('img#myImage').attr( "src", pictureList[index] );