[英]Form:select setting img src
我有這個表格:
<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="" />
with the form ? 是否可以有條件地將設置為以下形式? 我嘗試使用一些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);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.