简体   繁体   English

.onclick事件监听器通过div在页面加载后立即运行

[英].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. 这可能是一个nooby问题,但是此脚本已使我丧命:该脚本假定在单击鼠标时使用事件侦听器更改div权重。 The function changeWidth(i) works just fine. 函数changeWidth(i)可以正常工作。 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. 我不确定这是否是加载顺序的问题,这确实是一个最小的页面,脚本在页面末尾使用<script>标记运行。 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 . 您将立即使用()调用该函数,并且undefined函数的结果将分配给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); tile1.onclick = changeWidth(1); would invoked when body is being onload as plalx said. 如plalx所说,当body加载时会被调用。 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);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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