处理onclick事件;未捕获的typeError

时间:2014-11-06 15:30:47

标签: javascript onclick html5-canvas

我在这里遇到一个问题,我似乎也无法找到解决方案。我试图处理onclick事件,该事件只是在" tile"上切换颜色。这是我必须这样做的脚本:

<script>
    var GameTile = {
        createTile : function() {
            var newElement = document.createElement('div');
            newElement.id = "tileContainer";
            newElement.style.width = "100px";
            newElement.style.height = "100px";
            newElement.setAttribute("onclick", "GameTile.convertColor()");
            document.body.appendChild(newElement)

            var canvas = document.createElement('canvas');
            canvas.setAttribute("id", "tileCanvas");
            canvas.setAttribute("width", "100");
            canvas.setAttribute("height", "100");
            var ctx = canvas.getContext("2d");

            ctx.fillStyle = "#000000";
            ctx.fillRect (0, 0, 100, 100);

            ctx.fillStyle = "#969696";
            ctx.fillRect (7, 7, 86, 86);
            document.getElementById("tileContainer").appendChild(canvas);

        },

        convertColor : function() { 

            var canvas = document.getElementById('tileCanvas');
            var ctx = canvas.getContex("2d");

            ctx.fillStyle = "#969696";
            ctx.fillRect (0, 0, 100, 100);

            ctx.fillStyle = "#000000";
            ctx.fillRect (7, 7, 86, 86);

            document.getElementById("tileContainer").appendChild(canvas);
        }

    };
</script>

据我所知,函数convertColor()实际上是定义的,我调用它的方法不正确吗?或者我的实际语法不正确?

2 个答案:

答案 0 :(得分:2)

你在convertColor函数中输入错误。

var ctx = canvas.getContex("2d");

应该是

var ctx = canvas.getContext("2d");

注意缺少的那个。

答案 1 :(得分:0)

你应该交换这个

newElement.setAttribute("onclick", "GameTile.convertColor()");

到这个

newElement.addEventListener("click", "GameTile.convertColor()");
相关问题