search

Home  >  Q&A  >  body text

javascript - How to dynamically pass in a parameterized function to addEventListener?

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_u1582phpcn_u15822755 days ago829

reply all(5)I'll reply

  • phpcn_u1582

    phpcn_u15822017-05-18 10:52:01

    function myclick(i){
        return function(){
             alert(i)
        }

    The second parameter is passed to myclick(i)

    reply
    0
  • PHPz

    PHPz2017-05-18 10:52:01

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

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-05-18 10:52:01

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

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-18 10:52:01

    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)

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-18 10:52:01

    Change var to let

     window.onload = function () {
          for (let i = 1; i < 3; i++) {
            document.getElementById('myButton' + i)
              .addEventListener('click', () => {
                myClick(i)
              })
          }
        }

    reply
    0
  • Cancelreply