无法在 Rails 应用程序的回调中声明变量

Unable to declare variable within callback in Rails App

我目前正在使用 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 属性。然后,您将该函数(始终未定义)的 return 值分配给 img.

试试看:

let img = e.target.result

如果你真的想得到children的值,你可以试试

let img = avatarPreview.children[1].getAttribute('src')`