我有一些非常基本的代码,在屏幕上显示数字 1-10 的图像(标题为 1.jpg、2.jpg 等)。生成一个随机数,如果单击正确数字的图像,则会显示提示。如果点击了不正确的数字,我希望图像消失。我知道如何为每个图像使用单独的函数来实现这一点,但是在一个函数中完成这一切的最佳方法是什么?
最佳答案
首先:您的一些代码片段将有助于在此处给出合格的答案。
假设这样的东西是您的实际 html 结构(注意:如果您的 id
标签中有一个 img
,例如 <img src="1.jpg" id="1">
,您可以省略一些步骤):
<div id="image-wrapper">
<img src="1.jpg">
<img src="2.jpg">
<img src="3.jpg">
...
</div>
使用纯 JavaScript,您可以执行如下操作:
var rnd = ... //produce your random number
document.querySelectorAll("img").forEach(img => {
img.onclick = () => {
let src = img.src;
src = src.split("/"); //get an array of the source of your image
src = src[src.length - 1]; //get the last position inside the array (resembling the filename)
src = src.split("."); //split the filename by '.' (to separate filename and -type in the next step)
src = src[0];
src = parseInt(src); //make the extracted src and the random number you produced comparable by converting to int
if(rnd !== src) {
img.parentElement.removeChild(img);
} else {
alert("foo"); //your prompt
}
};
});
说明:使用方法document.querySelectorAll
您可以选择一组 html 节点(使用您可能习惯于 CSS 的相同选择器)。您现在可以使用 array.forEach
遍历此数组(有关进一步说明,请参阅 mdn)。在每个 img
您现在可以注册 onclick
-方法。鉴于你真的只有 src
的 img
作为鉴别器,您必须在下一步中从 src 中提取实际文件名。
将您的随机数与文件名进行比较后,您利用了一个事实,即您正在处理一个实际的 DOM 对象(在 forEach 循环中):您通过 Node.parentElement
获得父节点( mdn ) 您可以在其中发出删除其子项之一的命令(在我们的例子中是我们当前的图像)。
希望对您有所帮助 - 如需更多帮助,请提供有关该问题的更多信息:)
关于javascript - 单击它们后使编号图像消失的最简单方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58586781/