我有这样的表单:
<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
});
如果您使用jQuery,请执行以下操作
$(document).ready(function() {
var avatar = $("#avatar");
avatar.attr("src", "img/av" + avatar.attr("src").slice(-1) + ".png";
});
尝试下面的代码自动将属性应用到DOM元素
$("#avatar").each(function(index) {
var titleName = $(this).attr("src").toString().split('/').splice(-1,1);
var anchorIndex = "a:eq(" + index + ")";
$(anchorIndex).attr("title", titleName);
});
工作示例