总是一个循环,不好的做法?

时间:2017-04-14 09:26:52

标签: javascript ecmascript-6

我想知道当我想在我的元素上添加一个事件时是否需要创建一个forEach循环?

我的代码包含很多这样的循环:

  const $itemUpload = document.querySelectorAll('.js-file-upload'); // ~ 10 elements in my page

  // Image preview before upload
  [...$itemUpload].forEach((item) => {

    const $parent = item.closest('.js-upload-container');

    item.addEventListener('change', function() {

      const options = [
        this.parentNode.querySelector('.js-file-image'),
        this.files[0],
        this.parentNode.querySelector('.js-file-wording'),
      ];
      const upload = new Upload(...options);
      const $buttonClear = this.parentNode.querySelector('.js-remove-file');

      upload.previewFile();

      $parent.classList.add(activeClass);

    });

  });

与删除按钮的处理方式相同(forEach在.js-remove-file上进行抢劫。

我想知道这是否正确。当我的页面加载时,它会为可能无法创建的事件执行多个循环(单击以删除购物车中的项目,显示在所有页面上)。

你有什么建议吗?

谢谢社区!

0 个答案:

没有答案
相关问题