简体   繁体   English

文本的Javascript onclick事件

[英]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. 我有一个用document.write显示的Javascript对象数组,其中数组的每个元素都有一个可用于显示它的字符。

Is it possible to have an onclick event that modifies the data in the array? 是否可能有一个onclick事件会修改数组中的数据?

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. 在上面,WALL字符由#表示,而cycle()函数将#更改为空格,反之亦然。

I'm not sure how to connect the document.write symbol to the underlying data in the array. 我不确定如何将document.write符号连接到数组中的基础数据。

I was able to solve this by writing an HTML element with an onclick function instead of just a piece of text: 我可以通过编写带有onclick函数而不是一段文本的HTML元素来解决此问题:

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>");
    }
}

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

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