Javascript - Dynamically assign onclick event in the loop

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

I have very simple html page with js code:


    
        
    
    

        <         


        
7条回答
  •  -上瘾入骨i
    2020-11-27 20:26

    Consider the fact that when the onclick() function is executed, all it has is:

    showParam(optionPar);
    

    , verbatim. The optionPar will be resolve at the time the click event is executed, and at this point it most likely be the latest value you assigned to it. You should generally avoid passing variables in such a way.

    The problem you are trying to solve is best solved by re-writing the piece such as:

                btnShow.value = "Show Me Option";
                var optionPar = arrOptions[i];
                btnShow.optionPar = optionPar;
                btnShow.onclick = function(e) {
                    // if I'm not mistaking on how to reference the source of the event.
                    // and if it would work in all the browsers. But that's the idea.
                    showParam(e.source.optionPar);
                }
    

提交回复
热议问题