Javascript - Dynamically assign onclick event in the loop

前端 未结 7 1109
无人共我
无人共我 2020-11-27 19:38

I have very simple html page with js code:


    
        
    
    

        <         


        
7条回答
  •  北海茫月
    2020-11-27 20:33

    The accepted answer is correct but I feel that no real explanation was done.

    Let me try to explain, the issue here is classical missing closure.

    The variable 'i' is getting increased by 1 per loop iteration, and the on-click event actually is not being executed, whether only applied to the a element, it getting summarize up to the length of arrOptions which is 10.

    So, the loop continues up until 'i' is 10, Then, whenever the on-click event is being triggered, it takes the value of i which is 10.

    now, for the solution, in the solution we are using a closure, so that when we apply the value of 'i' to the on-click event of the a element, it actually gets the exact value of i at in time.

    The inner function of the onclick event create a closure where it references the parameter (arrOptions[i]), meaning what the actual i variable is at the right time.

    The function eventually closes with that value safely, and can then return its corresponding value when the on-click event is being executed.

提交回复
热议问题