assign onclick event to function

前端 未结 2 1537
栀梦
栀梦 2020-12-11 12:26

I want to call a function onclick and pass the event object to the function:

 progressBarOuter.onclick = function(e)  { 
     var x; if (!e) {
         x=win         


        
2条回答
  •  既然无缘
    2020-12-11 12:46

    Your:

    progressBarOuter.onclick = yt.progressBarClicked(e);
    

    doesn't yield the expected result, because you're not assigning the function yt.progressBarClicked to the onclick handler. You are actually calling the function and therefore assigning its return value to onclick.

    The shortest working thing you can get without breaking anything is this:

    progressBarOuter.onclick = function(e){
        yt.progressBarClicked((e || window.event).clientX); // pass the x position as a parameter
    };
    

    If you don't wrap it, yt.progressBarClicked will be called from the window object and therefore the value of this inside the function will be also set to the window object.

    Of course you could also handle the calculation of the x position inside the function and just pass the event to it:

    progressBarOuter.onclick = function(e){yt.progressBarClicked(e);};
    

提交回复
热议问题