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

Javascript 无法在Rails应用程序的回调中声明变量,javascript,turbolinks,Javascript,Turbolinks,我目前正在使用TruboLink开发Rails 6应用程序。我正在开发一个功能,用上传时选择的图像重新放置一个头像占位符。然而,奇怪的事情发生了,我声明了两个变量,一个是用over没有的值表示的 document.addEventListener('readystatechange', event => { if (event.target.readyState === "complete") { /** * Display the image in the file input

我目前正在使用TruboLink开发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')`

我最终使用了
let img=avatarPreview.children[1]
,但答案仍然有效。为什么返回未定义?setAttribute是setter。它的目的是设置值,而不是检索值。为此,必须使用getAttribute,它充当getter