我如何回忆其他函数中的自调用javascript函数?

时间:2017-09-25 13:08:40

标签: javascript html function html-lists addeventlistener

我不得不回忆一下自调用的方法,将新添加的元素添加到列表中

var textPop = document.getElementById('textPopper');
var elements = document.getElementById('our-list');

var reloader = (function reload() {
    document.querySelectorAll('ul li').forEach(function(click) {
        click.addEventListener("click", function() {
            textPop.innerHTML = this.innerHTML;
        })
    });

}
)();


function addItem() {
    elements.innerHTML += "<li> Something new stuff </li>";
    reloader();  //getting error here (Uncaught TypeError: again is not a function)
    }
            <h3 id="textPopper">Text popper </h3>
            <ul id="our-list">
                <li>First item </li>
                <li>Second item</li>
                <li>Third item</li>
                <li>Fourth item</li>
            </ul>
            <script src="my.js"></script>

3 个答案:

答案 0 :(得分:1)

IIFE执行并将结果分配给reloader,因此您无法调用reloader()

根据我的理解,您可能需要将函数本身分配给reloader,执行它,然后根据需要再次调用它。

var reloader = function() {
  document.querySelectorAll('ul li').forEach(function(click) {
    click.addEventListener("click", function() {
      textPop.innerHTML = this.innerHTML;
    })
  });
};

reloader();


function addItem() {
  elements.innerHTML += "<li> Something new stuff </li>";
  reloader(); //getting error here
}

答案 1 :(得分:1)

reloader不是自我调用函数。它是自调用函数的结果。如果在自调用函数中放置return 2,则重新加载器将为2。

你不希望它成为一个自我调用的功能。只需将重新加载器作为函数本身,然后在赋值后调用reloader()

答案 2 :(得分:0)

所以只需将其定义为函数而不是调用它。你遇到的问题是可变重载器保存了函数返回的内容。由于函数没有返回任何内容,因此它未定义。

var textPop = document.getElementById('textPopper');
var elements = document.getElementById('our-list');

var reloader = function() {
  document.querySelectorAll('ul li').forEach(function(click) {
    click.addEventListener("click", function() {
      textPop.innerHTML = this.innerHTML;
    })
  });
};

reloader()


function addItem() {
  elements.innerHTML += "<li> Something new stuff </li>";
  reloader();
}

window.setTimeout(addItem, 1000);
<h3 id="textPopper">Text popper </h3>
<ul id="our-list">
  <li>First item </li>
  <li>Second item</li>
  <li>Third item</li>
  <li>Fourth item</li>
</ul>
<script src="my.js"></script>

其他选项是使用事件委派,甚至不需要重新绑定事件。

var textPop = document.getElementById('textPopper');
var ul = document.getElementById('our-list');

//bind click event to the parent
ul.addEventListener("click", function(e) {
  //e.target will give you the li that was clicked on
  textPop.innerHTML = e.target.innerHTML;
})

function addItem() {
  var li = document.createElement("li")
  li.innerHTML = "Something new stuff"
  ul.appendChild(li);
}

window.setTimeout(addItem, 1000);
<h3 id="textPopper">Text popper </h3>
<ul id="our-list">
  <li>First item </li>
  <li>Second item</li>
  <li>Third item</li>
  <li>Fourth item</li>
</ul>
<script src="my.js"></script>