简体   繁体   中英

.onclick event listener over div running instantly after page load

this is probably a nooby question but this scrip is killing me: The script is suppose to change the div weight with an event listener while mouse click. The function changeWidth(i) works just fine. The problem is the event listeners trigger automatically when the page is loaded, and then it stop working. There is no console error.

var tile1 = document.getElementById("project_tile_01");
var tile2 = document.getElementById("project_tile_02");
var tile3 = document.getElementById("project_tile_03");

tile1.onclick = changeWidth(1);
tile2.onclick = changeWidth(2);
tile3.onclick = changeWidth(3);

function changeWidth(i){
    if(i==1){
        tile1.style.width=(200+"px");
        tile2.style.width=(150+"px");
        tile3.style.width=(150+"px");
        tile4.style.width=(150+"px");
        tile5.style.width=(150+"px");
        tile6.style.width=(150+"px");
    }else if(i==2){
        tile1.style.width=(150+"px");
        tile2.style.width=(200+"px");
        tile3.style.width=(150+"px");
        tile4.style.width=(150+"px");
        tile5.style.width=(150+"px");
        tile6.style.width=(150+"px");
    }else if(i==3){
        tile1.style.width=(150+"px");
        tile2.style.width=(150+"px");
        tile3.style.width=(200+"px");
        tile4.style.width=(150+"px");
        tile5.style.width=(150+"px");
        tile6.style.width=(150+"px");
}

I´m not sure if this is a problem of load order, This being really a minimal page the script is running with the < script > tag at the end of the page. Thanks in advance.

tile1.onclick = changeWidth(1);

You are immediately invoking the function with () and the result of the function which is undefined gets assigned to tile1.onclick .

Here's what you can do instead:

tile1.onclick = changeWidth.bind(null, 1);

您需要将changeWidth调用包装在一个函数中。

tile1.onclick = function(){changeWidth(1);}

This tile1.onclick = changeWidth(1); would invoked when body is being onload as plalx said. you can also do something like this.

This will be triggered only when the element would be clicked.

tile1.onclick = function (){
    changeWidth(1);
};

tile2.onclick = function (){
    changeWidth(2);
};

tile3.onclick = function (){
    changeWidth(3);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM