简体   繁体   中英

.Onclick and .addEventListener("click") both aren't limited to when the button is clicked

(New to programming, just recently took off my ProcessingJS wheels).

I'm trying to make a simple game of Tic Tac Toe; to accomplish this, I've made a nested for loop which defines, and draws 9 stylized buttons onto the web page, as well as push them into the [0] position in the first array of the Button Array (the other two positions within are occupied by booleans, which I'll use as indicators of whether the button is owned by playerX or playerO). I then try to make it so that when the button is pushed, using button[button number identifier, 0-8][0], it runs setSquare function, with argument equals to the number of the button (button number identifier).

But when I run the program, and check the console, it has already run the program before I even click anything (when I put it inside the for loop), or it works once, and then always defaults to the last else. I've been stuck at this for hours, and I've rummaged through so much. Any input? Also, I'm sorry if this isn't a good question. No hard feelings if it's taken down for whatever reason.

var setSquare = function(q) {
            if (button[q][1] === false && button[q][2] === false) {
                button[q][1] = true;
                console.log("button" + q + " now belongs to PlayerX");
            } else if (button[q][1] === false) {
                button[q][2] = true;
                console.log("button" + q + " now belongs to PlayerO");
            } else {
                millieBot();
            }
        }     

        var button = [ [/*0*/], [/*1*/], [/*2*/], [/*3*/], [/*4*/], [/*5*/], [/*6*/], [/*7*/], [/*8*/] ];  //Just the place where I'm gonna put all the buttons/squares, alongside the fact of whether they are owned by X or O. (Inserted by a for loop, to make it look something like: button = [document.createElement("button"), false, false], [...])

        button[0][0].addEventListener("click", setSquare(0));

Important note: I am using purely javascript and HTML (JS DOM) for now, since I want to first get better at the basics, before I move onto jQuery or any of that other stuff.

addEventListener expects a reference to a function and not a function call.
So you just write (without the parenthesis)

button[0][0].addEventListener("click", setSquare);

Because you want to pass an argument to your function you can wrap it in an anonymous function

button[0][0].addEventListener("click", function() { setSquare (0); });

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