【问题标题】:Unable to declare variable within callback in Rails App无法在 Rails 应用程序的回调中声明变量
【发布时间】: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


    【解决方案1】:

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

    试试吧:

    let img = e.target.result
    

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

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

    【讨论】:

    • 我最终使用了let img = avatarPreview.children[1],但答案仍然有效。
    • 为什么返回 undefined?
    • setAttribute 是一个设置器。它的目的是设置值,而不是检索它们。为此,您必须使用 getAttribute,它充当 getter
    猜你喜欢
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    • 2018-09-22
    • 2011-12-26
    相关资源
    最近更新 更多