gpt4 book ai didi

javascript - 在 Javascript 中处理事件

转载 作者:行者123 更新时间:2023-12-02 16:09:06 24 4
gpt4 key购买 nike

我对 Javascript 世界还很陌生。我有三张照片:

1. mango.jpg
2. apple.jpg
3. pineapple.jpg.

我想做的是,每当我点击浏览器中的图像时,它就会变得模糊。我有 3 个额外的模糊图片,名为:

1.apple_blur.jpg
2.mango_blur.jpg
3.pineapple_blur.png

这是我下面的代码(我正在尝试以最短的方式做到这一点)

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> I'm alive! </title>
<script>
window.onload = pageLoadedHandler;
function pageLoadedHandler() {
blur_images=[{id_pic:["apple","apple_blur.jpg"]},{id_pic:["mango","mango_blur.jpg"]}, {id_pic:["pineapple","pineapple_blur.png"]}];
for(i=0;i<=blur_images.length;++i) {
blur_image=blur_images[i];
window[blur_image.id_pic[0]]=document.getElementById(blur_image.id_pic[0]);
window[blur_image.id_pic[0]].onclick=blur_func;
}
function blur_func() {
for(i=0;i<=blur_images.length;++i) {
blur_image=blur_images[i];
window[blur_image.id_pic[0]]=document.getElementById(blur_image.id_pic[0]);
window[blur_image.id_pic[0]].src=blur_image.id_pic[1];
}
}
}
</script>
</head>
<body>
<img src="apple.jpg" id="apple"></img>
<img src="mango.jpg" id="mango"></img>
<img src="pineapple.png" id="pineapple"></img>
</body>
</html>

当我在浏览器中单击图像时,所有图像都会变得模糊,而不是该特定图像(这是因为每当我单击任何图像时,处理程序“blur_func”都会迭代并用模糊版本图像替换所有图像.

如何重写代码以告诉 blur_func 处理程序仅用模糊的苹果图像替换苹果图像?

最佳答案

编辑:

您的代码中有一些更正:

window.onload = pageLoadedHandler;
/* moved outside to make it global and used `var` keyword */
var blur_images=[{id_pic:["apple","apple_blur.jpg"]},{id_pic:["mango","mango_blur.jpg"]}, {id_pic:["pineapple","pineapple_blur.png"]}];
function pageLoadedHandler() {
for(var i=0;i<blur_images.length;i++) { //removed `=` sign and using `i++` instead of `++i`
// ^ ^^
document.getElementById(blur_images[i].id_pic[0]).onclick=blur_func;
}
}
function blur_func(e) {
e = (e || window.event); //get the right event
var id = (e.target || e.srcElement).id; //get the clicked image id
var blur_image;
for(var i=0;i<blur_images.length;i++) { //removed `=` sign and using `i++` instead of `++i`
// ^ ^^
if(id === blur_images[i].id_pic[0]){//got the one clicked
blur_image=blur_images[i];
break;
}
}
document.getElementById(blur_image.id_pic[0]).src=blur_image.id_pic[1];
}

P.S.每当您需要声明变量以避免意外行为时,请使用 var 关键字。

关于javascript - 在 Javascript 中处理事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30418423/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com