javascript - How to dynamically pass in a parameterized function to addEventListener?
phpcn_u1582
phpcn_u1582 2017-05-18 10:50:01
0
5
824

There is an unadopted answer to "Xiao Xiao Yu Xie", which is also useful, but I don't know the specific usage of let yet. Sorry, I really want to adopt two.

The result must be
click button1 alert(3)
click button2 alert(3)

How to modify the code to make
click button1 alert(1)
click button2 alert(2)

I feel that this problem is a bit similar to the classic closure problem of settimeout, but I can't think of any solution.

Please give me some advice.

phpcn_u1582
phpcn_u1582

reply all(5)
phpcn_u1582
function myclick(i){
    return function(){
         alert(i)
    }

The second parameter is passed to myclick(i)

PHPzhong

Save parameters in the attributes of each button element.
or use let

我想大声告诉你

<button id='myButton1' data-info='abc'></button> After clicking the button, get the attributes in the button's data-info

曾经蜡笔没有小新

Jquery generally operates the DOM. When rendering, it is usually spliced ​​onto the DOM in the data-* format, and then it is obtained and then used $(this).attr(key)

过去多啦不再A梦

Change var to let

 window.onload = function () {
      for (let i = 1; i < 3; i++) {
        document.getElementById('myButton' + i)
          .addEventListener('click', () => {
            myClick(i)
          })
      }
    }
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template