Event handler scope in Javascript

后端 未结 3 1341
臣服心动
臣服心动 2021-01-14 10:03

This is probably an easy question but I can\'t figure out the best answer for it.

I have 10

elements on screen. Each of them has a cli
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-14 10:24

    So your problem is the nature of doing async code inside of loops as the other post said. In your case though there's altogether a better way to solve this problem and that's using event delegation.

    document.body.onclick = function(e) {
      if (e.target.tagName.toLowerCase() === "div") {
        alert( "Element " + e.target.id );
      }
    }
    

    If you had jQuery you could do this:

    $(document.body).on("click", "div", function() {
      alert($(this).attr("id"));
    });
    

    For more info check out this article: http://www.sitepoint.com/javascript-event-delegation-is-easier-than-you-think/

    Obviously jQuery and other libs handle this stuff automatically as well.

提交回复
热议问题