association.js:39未捕获的TypeError:无法读取未定义的属性“ classList”

时间:2019-09-21 12:53:28

标签: javascript

对于一个项目,我必须开发一段代码,但我做不到。最初,这段代码使我可以切换某种形式的4个可点击元素,并且效果很好。

const choices = document.querySelectorAll('.clickable');

const toggleActiveClass = (event) => {
  event.currentTarget.classList.toggle('active');
};

const toggleActiveOnClick = (choice) => {
  choice.addEventListener('click', toggleActiveClass);
};

choices.forEach(toggleActiveOnClick);

但是,现在我必须确保当我选择前两个元素中的一个或另一个时,不能切换另一个,而下一个2不能切换。我尝试了这段代码,但是当我打开控制台时在chrome工具中,我收到此帖子标题中的错误消息。这是有问题的代码:

const upsell = document.querySelector('#test1 > .clickable');
const crossell = document.querySelector('#test2 > .clickable');
const standard = document.querySelector('#test3 > .clickable');
const discount = document.querySelector('#test4 > .clickable');

const choices = [ upsell, crossell, standard, discount ];

const toggleActiveClass = (event) => {
  if (event === upsell) {
    event.currentTarget.classList.toggle('active');
    crossell.classList.remove('active');
  } else if (event === crossell) {
    event.currentTarget.classList.toggle('active');
    upsell.classList.remove('active');
  } else if (event === standard) {
    event.currentTarget.classList.toggle('active');
    discount.classList.remove('active');
  } else if (event === discount) {
    event.currentTarget.classList.toggle('active');
    standard.classList.remove('active');
  }
};

const toggleActiveOnClick = (choice) => {
  choice.addEventListener('click', toggleActiveClass);
};


choices.forEach(toggleActiveOnClick);

这是对应的html

<div class="form-group">
          <label for="bundle-type">Bundle Type</label>
          <div class="d-flex flex-wrap justify-content-center pt-4">
            <div id="test1">
              <div class="clickable">
                <i class="fas fa-shopping-cart"></i>
                <small>Upsell</small>
              </div>
            </div>
            <div id="test2">
              <div class="clickable">
                <i class="fas fa-cart-plus"></i>
                <small>Cros-sell</small>
              </div>
            </div>
          </div>
          <label for="bundle-type">Offer Type</label>
          <div class="d-flex flex-wrap justify-content-center pt-4">
            <div id="test3">
              <div class="clickable">
                <i class="fas fa-gift"></i>
                <small>Standard</small>
              </div>
            </div>
            <div id="test4">
              <div class="clickable">
                <i class="fas fa-percent"></i>
                <small>Discounted</small>
              </div>
            </div>
          </div>
        </div>

和CSS

.clickable i {
  font-size: 24px;
  margin-bottom: 10px;
}

.clickable:hover i {
  color: #167FFB;
}

.clickable.active {
  color: inherit;
  border-color: inherit;
}

.clickable.active i {
  color: #0F60C4;
}

1 个答案:

答案 0 :(得分:0)

将所有event ===更改为event.currentTarget ===,因为这是保存元素引用的地方。