首页 > 解决方案 > 无法在 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则无法正常工作。

为什么我不能在回调中声明变量?我想了解不要太在意让它工作。

在此处输入图像描述

标签: javascriptturbolinks

解决方案


您正在调用setAttribute以分配e.target.resultsrc元素的属性。然后,您将该函数(始终未定义)的返回值分配给img.

请尝试:

let img = e.target.result

如果你真的想从孩子身上得到价值,你可以试试

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

推荐阅读