簡體   English   中英

Let 錯誤的重新聲明 - 如何找到它被重新分配的位置?

[英]Redeclaration of Let error - How to find where it's being reassigned?

控制台錯誤 - “Uncaught SyntaxError: let sectionSelector 的重新聲明”

代碼 -

<script type="text/javascript">
  const sectionSelector = '#shopify-section-{{ section.id }}';
  
  let collectionSelectors = document.querySelectorAll(`${sectionSelector} .recommendations__collection-selector`);
  
  for (let collectionSelector of collectionSelectors) {
    let blockId = collectionSelector.dataset.blockId;

    let collectionCarousel = document.querySelector(`${sectionSelector} .recommendations__collection[data-block-id="${blockId}"]`);
    let otherCarousels = document.querySelectorAll(`${sectionSelector} .recommendations__collection:not([data-block-id="${blockId}"])`);

    collectionSelector.addEventListener('click', () => {

      for (let otherCarousel of otherCarousels) {
        otherCarousel.classList.remove('active');
      }

      for (let collectionSelector of collectionSelectors) {
        collectionSelector.classList.remove('active');
      }

      collectionSelector.classList.add('active');
      collectionCarousel.classList.add('active');

      window.dispatchEvent(new Event('resize'));
    })
  }
</script>

我首先將let sectionSelector更改為const ,將錯誤更改為 collectionSelectors。 這是我在網站上對 sectionSelector 的唯一引用,即使我只有一行,錯誤仍然存在 -

  let sectionSelector = '#shopify-section-{{ section.id }}'; 

所以我的問題是如果沒有任何新聲明,如何重新分配變量。 我開始認為它與使用 for...of 的 for 循環有關?

在第一個循環中聲明了一個迭代變量collectionSelector ,然后在事件偵聽器中的循環中以相同的方式聲明迭代器,但是第二個循環共享第一個循環的scope,只需在第二個循環中更改名稱

for (const item of collectionSelectors) {
    item.classList.remove('active');
}

您在for loop中兩次聲明collectionSelector變量

for (let collectionSelector of collectionSelectors) {// fist time
    let blockId = collectionSelector.dataset.blockId;

    let collectionCarousel = document.querySelector(`${sectionSelector} .recommendations__collection[data-block-id="${blockId}"]`);
    let otherCarousels = document.querySelectorAll(`${sectionSelector} .recommendations__collection:not([data-block-id="${blockId}"])`);

    collectionSelector.addEventListener('click', () => {

      for (let otherCarousel of otherCarousels) {
        otherCarousel.classList.remove('active');
      }

      for (let collectionSelector of collectionSelectors) { // 2nd time
        collectionSelector.classList.remove('active');
      }

      collectionSelector.classList.add('active');
      collectionCarousel.classList.add('active');

      window.dispatchEvent(new Event('resize'));
    })
  }

我的第一個for loop scope 已經有一個名為collectionSelector的變量,這就是出現錯誤的原因。 將其更改為另一個變量名,應該修復錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM