简体   繁体   中英

Javascript onclick event for text

I have an array of objects in Javascript that I'm displaying with document.write, where each element of the array has a single character that can be used to display it.

Is it possible to have an onclick event that modifies the data in the array?

var initializeArray = function(){
    for(var i = 0; i < HEIGHT; i++){
        maze[i] = new Array(WIDTH)
    }

    //Initialize all to walls
    for(var i = 0; i < HEIGHT; i++){
        for(var j = 0; j < WIDTH; j++){
            maze[i][j] = new Cell(cellType.WALL);
            maze[i][j].onclick = cycle; //The line in question that does not work
        }
    }
}

var printMaze = function(){
    for(var i = 0; i < HEIGHT; i++){
        for(var j = 0; j < WIDTH; j++){
            document.write(symbols[maze[i][j].type]);
        }
        document.write("<br>");
    }
}

In the above, the WALL character is represented by a #, and the cycle() function changes a # to a space, and vice-versa.

I'm not sure how to connect the document.write symbol to the underlying data in the array.

I was able to solve this by writing an HTML element with an onclick function instead of just a piece of text:

var printCell = function(cell){
    document.write("<span class='cell' onClick='cycle(this)'>" + symbols[cell.type]) + "</span>";
}

var printMaze = function(){
    for(var i = 0; i < HEIGHT; i++){
        for(var j = 0; j < WIDTH; j++){
            printCell(maze[i][j]);
        }
        document.write("<br>");
    }
}

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