[英]Show image depending on select option with custom value attribute
我想达到的目标:
根据选择框的选择显示图像。 但是我不想采用属性value=""
,而是想采用自定义属性data-img=""
。
这是我实际拥有的代码,但是没有用:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script>
function showFormatImage() {
var image = document.getElementById("itemImage");
image.src = $('select[name=itemImage] option:selected').data('img');
return false;
}
document.getElementById("itemImage").onchange = showFormatImage;
</script>
</head>
<body>
<select id="itemImage" name="itemImage">
<option data-img="first.png">First</option>
<option data-img="second.png">Second</option>
<option data-img="third.png">Third</option>
</select><br>
<img id="itemImage" src="">
</body>
</html>
没有显示图像。 有人知道怎么了吗?
PS:如果有非JavaScript解决方案,那会更好,但我认为没有。
var image = document.getElementById("itemImage");
var image
是select,而不是img
,也是itemImage
在执行时不存在,因此未放置事件处理程序。
您应该将代码更改为:
<html>
<head>
<script>
window.onload = function() {
document.getElementById("itemImage").onchange = showFormatImage;
};
function showFormatImage() {
var image = document.getElementById("changeImage");
image.src = $('select[name=itemImage] option:selected').attr('data-img');
return false;
}
</script>
</head>
<body>
<select id="itemImage" name="itemImage">
<option data-img="first.png">First</option>
<option data-img="second.png">Second</option>
<option data-img="third.png">Third</option>
</select><br>
<img src="" id='changeImage'/>
</body>
</html>
jQuery解决方案:
$(document).ready(function(){
$('#itemImage').change(function(){
var src = $(this).find('option:selected').attr('data-img');
$('img#changeImage').attr('src',src);
});
});
应该用.attr(data-img)替换.data函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.