合并事件侦听器和单击处理程序

时间:2018-04-03 21:37:31

标签: javascript

我有一个脚本可以切换两个div的内容显示。我目前在每个链接上使用一个事件列表器和一个单击处理程序,但需要将它们合并为一个。最后,应该有一个单击处理程序,它根据单击的链接查找id([1] "s" ")" "f" "f" "t" "S" "" en)并根据该视图切换视图,而不是以下实现。我有点困惑于如何使用一个来查找任一链接的ID并根据它进行切换。



de

const Terms = {
  bindEvents () {
    this.enTrigger.addEventListener('click', (e) => {
      this.langToggle(this.englishContent)
      this.enTrigger.classList.add('active')
      this.frTrigger.classList.remove('active')
    })
    this.frTrigger.addEventListener('click', (e) => {
      this.langToggle(this.frenchContent)
      this.frTrigger.classList.add('active')
      this.enTrigger.classList.remove('active')
    })
  },

  init () {
    this.englishContent = document.getElementById('english-terms')
    this.frenchContent = document.getElementById('french-terms')
    this.enTrigger = document.getElementById('en')
    this.frTrigger = document.getElementById('fr')
    this.bindEvents()
  },

  langToggle (id) {
    this.englishContent.style.display = 'none'
    this.frenchContent.style.display = 'none'
    id.style.display = 'block'
  }
}

document.addEventListener('DOMContentLoaded', () => {
  Terms.init()
})

.trigger.active {color:red;}




1 个答案:

答案 0 :(得分:1)

你说的。您创建一个侦听器并检查id:

const Terms = {
  bindEvents () {
    var listener = (e) => {
      var id = e.target.id; // Get the id of the element that was clicked
      if (id && this.buttons.hasOwnProperty(id)) { // Check if an element was actually selected
        this.buttons[id].classList.add('active');
        for (var i in this.buttons) { // Loop through the other elements and disable them (only one but to optimize if you add more).
          if (i != id) {
              this.buttons[i].classList.remove('active');
          }
        }
        this.langToggle(id);
      }
    };
    var languages = document.getElementById("terms-nav");
    languages.addEventListener("click", listener);
  },

  init () {
    this.buttons = {
      en: document.getElementById('en'),
      fr: document.getElementById('fr')
    };
    this.terms = {
      en: document.getElementById('english-terms'),
      fr: document.getElementById('french-terms')
    };
    this.bindEvents();
  },

  langToggle (id) {
    for (var i in this.terms) {
      if (i != id) {
        this.terms[i].style.display = "none";
      }
    }
    this.terms[id].style.display = "block";
  }
}

document.addEventListener('DOMContentLoaded', () => {
  Terms.init()
})
.trigger.active {color:red;}
<div class="terms-nav" id="terms-nav">
  <a class="trigger active" id="en">English</a>
  <a class="trigger" id="fr">French</a>
</div>
<div id="english-terms">English Content</div>
<div id="french-terms" style="display:none">French Content</div>

通过这种方式,您还可以将侦听器仅附加到父级(最好只有一个事件处理程序而不是2个或更多),并且它将在单击子级时进行处理。