简体   繁体   English

添加onClick事件动态DOM对象

[英]Adding onClick event dynamic DOM Object

I'm coding basic balloon game. 我正在编写基本的气球游戏。 Balloons are created dynamically into the canvas. 气球是动态创建到画布中的。 Everything is ok but I could not add onclick event to hide the balloon. 一切正常,但我无法添加onclick事件来隐藏气球。 First function to start game is " Baslat ()". 开始游戏的第一个功能是“ Baslat ()”。 Here is my codes 这是我的密码

var canvas; 
var sev = 1;
var zorluk = 3;
var ctx;

function Baslat() {
    var x;
    for (x = 1; x <= sev*zorluk; x++) {
        BalonYap(x);
    }
}

function seviye(a) {
    sev = a.value;
}

function BalonYap(id) {

    var img = new Image();
    img.src = "balon.png";
    img.id = "balon_"+id;
    img.onload = BalonLoad(img); // works
    img.onclick = Patlat(id); // doesn't work

}

function BalonLoad(img) {
    var rnd1 = Math.floor(Math.random() * 750)+10;
    var rnd2 = Math.floor(Math.random() *350)+10;
    canvas = document.getElementById('myCanvas');
    context = canvas.getContext("2d");
    context.drawImage(img, rnd1, rnd2);
}

function Patlat(img) {
    alert();
}

You need to assign function to event handlers. 您需要将功能分配给事件处理程序。 If you give arguments to a function it's called. 如果为函数提供参数,则会调用该函数。 You can try this factory method (you can give arbitrary parameters to the wrapping function and use them inside the returned function's closure): 您可以尝试使用这种工厂方法(您可以为包装函数提供任意参数,并在返回的函数的闭包中使用它们):

function BalonLoad(img) {
    return function() {
        var rnd1 = Math.floor(Math.random() * 750)+10;
        var rnd2 = Math.floor(Math.random() *350)+10;
        canvas = document.getElementById('myCanvas');
        context = canvas.getContext("2d");
        context.drawImage(img, rnd1, rnd2);
    }
}

Part of the issue here is that you are attempting to assign an event callback on an element that does not exist in the DOM. 这里的部分问题是您试图在DOM中不存在的元素上分配事件回调。 You are only drawing to the canvas. 您仅在画布上绘画。 A click event will need to be applied to the canvas element. click事件将需要应用于canvas元素。 You will need to save the coordinates of each balloon, and use that to find the appropriate balloon when the canvas is clicked. 您将需要保存每个零件序号的坐标,并在单击画布时使用该坐标找到合适的零件序号。

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

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