Javascript 如何检测是否单击了图像
我正在尝试检测是否单击了图像。为了给一些背景知识,我正在制作一个cookieclicker游戏,如果你点击它10次,就会出现一个新的图像,它会给你双倍的分数。对于我使用的第一个图像Javascript 如何检测是否单击了图像,javascript,Javascript,我正在尝试检测是否单击了图像。为了给一些背景知识,我正在制作一个cookieclicker游戏,如果你点击它10次,就会出现一个新的图像,它会给你双倍的分数。对于我使用的第一个图像 document.querySelector('#clickme1').onclick=scooore; 然后,我使用以下功能添加新图像: function show_image(src, width, height, alt) { var img = document.createElement("img
document.querySelector('#clickme1').onclick=scooore;
然后,我使用以下功能添加新图像:
function show_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
document.body.appendChild(img);
}
我的问题是如何添加到变量(scree)中,因为它是局部变量,第一种方法需要使用整个diff函数
function scooore() {
scree = scree + 1;
document.getElementById("scorez").innerHTML = "Image has been clicked " + scree + " times";
在这一可能只有一行代码的解决方案上工作了40多分钟,但找不到解决方案,因此求助于stack overflow的好人除了我在下面发布的代码之外,如果您为每个图像(无论是对象还是另一个数组)都有一个数据数组,那么在您继续开发项目时真正有帮助的是
//放在外部,这样图像可以更改而不是克隆
var img=document.createElement(“img”)
//填写初始图像规格
img.src=src
img.width=宽度
img.height=高度
img.alt=alt
函数显示图像(src、宽度、高度、高度){
img.src=src
img.width=宽度
img.height=高度
img.alt=alt
}
变量scree=0
函数scooore(){
碎石++
document.getElementById(“scorez”).innerHTML=“图像已被单击”+scree+“次”
//如果分数可以被10整除
如果(屏幕%10==0){
显示图像(src、宽度、高度、高度)
}
}
document.querySelector(“#clickme1”).onclick=scroore()
要使用与第一个相同的新图像句柄吗?您可以将scree=0
初始化为全局,这样就可以在scree
内部的任何本地scooore
中访问它。如果你能提供一个有帮助的可复制的例子。@Heribertolougo,我做了,到目前为止还不错,但是我怎样才能正确地调用添加事件侦听器呢?当我刚刚添加:document.querySelector('#newid').onclick=scooore;在document.querySelector(“#clickme1”)下。onclick=scooore;它只是永远不会运行