javascript - 无法在 Rails 应用程序的回调中声明变量
问题描述
我目前正在使用 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
则无法正常工作。
为什么我不能在回调中声明变量?我想了解不要太在意让它工作。
解决方案
您正在调用setAttribute
以分配e.target.result
给src
元素的属性。然后,您将该函数(始终未定义)的返回值分配给img
.
请尝试:
let img = e.target.result
如果你真的想从孩子身上得到价值,你可以试试
let img = avatarPreview.children[1].getAttribute('src')`
推荐阅读
- javascript - Javascript / HTML计算器,需要其他方法来计算结果
- office-js - 对 getUserIdentityTokenAsync() 的 Office API 调用返回一个空令牌
- html - 使用 mpdf 6.1 加载 PDF 文档失败
- javascript - Typescript HTML5 API 类型
- python - 使用 Python 脚本将 JSON 文件推送到 elasticsearch:有效但在 Kibana 中不显示
- swift - CUIThemeStore:在设备上的 Watch Extension 上没有注册 id=0 的主题
- excel - 在 excel 中创建在 Chrome 中打开的超链接
- ios - UIView 到 UIImage 使用 UIGraphicsImageRenderer 错误地用 alpha 渲染图像
- angular - 在 Angular Universal 中使用 Cookies(对于 Angular 6 )
- python - Python / Numpy根据第一列值将2D数组重塑为3D数组