2 回答
TA贡献1841条经验 获得超3个赞
如果你有 jQuery,请使用它
在这里,我使用一个对象来匹配选择,并使用公共类来允许更改任一下拉列表
const images = {
"A1": "https://i.imgur.com/FHWSAJt.png",
"B1": "https://ih1.redbubble.net/image.1666904566.4117/flat,128x,075,f-pad,128x128,f8f8f8.jpg",
// ...
}
$(function() { // on page load
const defaultImage = $('#image1').attr('src'); // grab the image from the HTML
$('.form-image1').on('change', function() { // any of the selects
const opt1 = $("#option1").val();
const opt2 = $("#option2").val();
const image = images[`${opt1}${opt2}`] || defaultImage; // use default if not found
$('#image1').attr('src', image);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img id="image1" src="https://www.w3schools.com/images/lamp.jpg" alt="Lamp" width="32" height="32" />
<select class="form-image1" id="option1" name="option1">
<option value="">Please select</optopn>
<option value="A">Blush</option>
<option value="B">Black</option>
<option value="C">C</option>
</select>
<select class="form-image1" id="option2" name="option2">
<option value="">Please select</option>
<option value="1">Horizontal Stripes</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
至于错误:
您遇到了括号问题。
) };
应该
} }); });
.on("change")
也不是.on("onchange")
最后$('#form-image1')
是访问 ID =“form-image1”的元素,但只有 CLASS =“form-image1”的元素,并且需要使用点来访问$('.form-image1')
TA贡献2051条经验 获得超10个赞
$('#form-image1').on('onchange', function()- 这里的form-image1id 不存在于 HTML 中,您还必须修改onchange为change.
$(document).ready(function() {
$('#option1').on('change', function() {
var option1 = document.getElementById("option1");
var option2 = document.getElementById("option2");
var option1selection = option1.options[option1.selectedIndex].value;
var option2selection = option2.options[option2.selectedIndex].value;
// Based on the condition update the image source
$('#image1').attr('src', 'https://i.imgur.com/FHWSAJt.png');
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img id="image1" src="https://www.w3schools.com/images/lamp.jpg" alt="Lamp" width="32" height="32" />
<select class="form-image1" id="option1" name="option1">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<select class="form-image1" id="option2" name="option2">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
添加回答
举报