我有这个表格:
<form action="php script" method="post" accept-charset="UTF-8">
<select class="form-control" name="image" id="image" onclick='edit()' >
<option>Image 1
<option>Image 2
<option>Image 3
<option>Image 4
<option>Image 5
<option>Image 6
<option>Image 7
</select>
</form>
我有这张图片:
<img id="avatar" alt="" />
是否可以使用表单有条件地设置img src? 我尝试使用一些js,例如:
<script type="text/javascript">
var imId = document.getElementById("image").src;
document.getElementById("avatar").src = "img/av"+imId.slice(-1)+".png";
</script>
但是它不起作用......请问有什么提示吗?
最佳答案
为什么不在选项中使用数据属性来存储图像的路径?
<select class="form-control" name="image" id="image">
<option data-source="/first_path/">Image 1</option>
<option data-source="/second_path/">Image 2</option>
<option data-source="/third_path/">Image 3</option>
<option data-source="/fourth_path/">Image 4</option>
<option data-source="/fifth_path/">Image 5</option>
<option data-source="/sixth_path/">Image 6</option>
<option data-source="/seventh_path/">Image 7</option>
</select>
然后在下拉列表中使用 change
事件来获取所选选项的源。
$('#image').change(function(){
var path = $(this).find('option:selected').data('source'); //get source of selected option and store it in variable path
$('#avatar').attr('src', path); //specify image's source to be variable path
});
关于javascript - 表格:select setting img src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31765583/