【发布时间】:2020-04-16 23:23:08
【问题描述】:
我目前正在使用 trubolinks 开发 Rails 6 应用程序。我正在开发一个功能,用上传时选择的图像重新放置头像占位符。但是,发生了一些奇怪的事情,我声明了两个变量,一个是用 over 没有的值声明的。
document.addEventListener('readystatechange', event => {
if (event.target.readyState === "complete") {
/**
* Display the image in the file input when added to the form.
* Replace avatar with image selected.
*/
const profileAvatarBlock = document.getElementById('profile-avatar');
function showImage(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
let avatarPreview = document.getElementById('profile-avatar-preview');
let img =avatarPreview.children[1].setAttribute("src", e.target.result);
debugger;
['width', 'height'].forEach(attribute => {
img.removeAttribute(attribute)
});
debugger;
};
reader.readAsDataURL(input.files[0]);
}
}
profileAvatarBlock.addEventListener('change', function() {
showImage(this);
})
}
});
起初我以为是因为 turbolinks 所以我添加了"turbolinks:load", 但这并没有改变任何东西。当我检查avatarPreview 时,我回到调试器中,但是当我检查img 时,我得到了未定义。如果我运行avatarPreview.children[1].setAttribute("src", e.target.result);,我也会将其返回,但如果我将其分配给img,则无法正常工作。
为什么我不能在回调中声明变量?我想明白不要太在意让它工作。
【问题讨论】:
标签: javascript turbolinks