javascript - 删除函数工作一次,然后从其余元素中卸载 [JavaScript 模块]

标签 javascript html node-modules object-literal

我一直在练习使用 JavaScript 模块,我需要有人帮助我理解为什么删除功能无法正常工作。我假设添加一个人后,绑定(bind)中会发生一些事情?

(function() {
  let people = {
    people: ['will', 'john'],
    init() {
      this.cacheDOM();
      this.render();
      this.bindingEvents();
    },
    cacheDOM() {
      this.$inputVal = document.getElementById('input');
      this.$target = document.getElementById('template');
      this.$button = document.getElementById('btn');
      this.$DOMLis = document.getElementsByClassName('elems');
    },
    bindingEvents() {
      this.$button.addEventListener('click', this.addName.bind(this));
      //Adding event listener "delete" to the lis
      this.$keys = Object.keys(this.$DOMLis);
      this.$keys.map(val => {
        this.$DOMLis[val].addEventListener('click', this.remove.bind(this));
      });
    },
    render() {
      this.$target.innerHTML =
        '<ul>' +
        this.people
          .map((val, i) => {
            return `<li key=${i} class='elems' name='${val}'>${val}</li>`;
          })
          .join('') +
        '</ul>';
    },
    addName() {
      this.people.push(this.$inputVal.value);
      this.render();
    },
    remove(e) {
      let index = parseInt(e.target.getAttribute('key'));
        this.people.splice(index, 1);


      this.render();
    },
  };

  people.init();
})();

这是 HTML

<div id="root">
  <div id="template"></div>
  <input id="input" type="text" />
  <button id="btn">un</button>
</div>

<script type="text/javascript" src="./script.js"></script>


addPerson 函数似乎可以与其他所有函数一起正常工作,但删除函数则不然。

最佳答案

您的bindingEvents()函数向每个 elems 添加一个单击事件监听器由您 render() 创建功能。下次render()被调用(在添加或删除之后),所有 elems被删除并重新创建,但监听器不会重新添加。 您需要更改 render() 的方式正在工作,或将单击事件监听器重新添加到每个 elems ,每次渲染时。

关于javascript - 删除函数工作一次,然后从其余元素中卸载 [JavaScript 模块],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60233121/

相关文章:

javascript - 为什么 ReactJS 的性能不如原始 JS 那样简单、愚蠢的概念证明?

javascript - Framework7 中的导航栏覆盖

html - 在 Bootstrap 中居中文本

html - 如何使带有注释的 HTML 代码处于非事件状态

node.js - 需要子文件夹中的 node_module

javascript - 如何让 Protractor 按下ESCAPE键?

javascript - 使用 ng-repeat 在 ion-item 中显示 JSON 文件的内容

c++ - Node 扩展问题

javascript - 如何在React Native中使用FlatList和webView显示数据?

javascript - 如何在 Typescript 1.8 中包含未类型化的节点模块?