我有一段 jQuery 可以在保存用户表单时更改隐藏字段的值,如下所示:
$('button').click(function () {
$("#avatar-val").val($(".avatar-view>img").prop('src'));
});
我还需要它反向工作(某种程度上)。这样当用户返回到那里的用户页面时,它会在隐藏字段中获取 whats 的值并将其放入默认头像图像的 img
src(在 div avatar -view
, picture.jpg
)
我尝试添加以下内容,但无法正常工作
$(document).ready(function() {
$(".avatar-view>img").src($("#avatar-val").prop('src'));
});
<div class="avatar-view" title="Change the avatar">
<button class="btn btn-primary btn-block avatar-save">
Change Avatar
</button>
<img src="/scripts/cropper/img/picture.jpg" alt="Avatar" >
</div>
<input name="avatar" value="../cropper/img/20150729105134.png" id="avatar-val" type="hidden">
最佳答案
.src()
在 jQuery 中不存在,你应该使用 .prop(propertyName, value)
功能
Set one or more properties for the set of matched elements.
并使用 .val()
方法读取 input
值。
使用
$(".avatar-view > img").prop('src', $("#avatar-val").val());
$(document).ready(function() {
$(".avatar-view > img").prop('src', $("#avatar-val").val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="avatar-view" title="Change the avatar">
<button class="btn btn-primary btn-block avatar-save">
Change Avatar
</button>
<img src="https://www.gravatar.com/avatar/7839089cd91dc5cc5eb1e0cdbf3312ed" alt="Avatar">
</div>
<input name="avatar" value="https://www.gravatar.com/avatar/1a7926d223f025242d8ec5b120cc3e68" id="avatar-val" type="hidden">
关于javascript - 在页面加载时更改 img src 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31697756/