简体   繁体   English

如何将新图像拼接到我要删除的图像所在的同一 position 中的数组中并显示此图像

[英]How do I splice a new image into an array in the same position that the image that I want to remove is in and to display this image

I have an array of images.我有一系列图像。 Each image is clickable and generates a message.The images are in a random array.每个图像都是可点击的并生成一条消息。图像位于随机数组中。 This all works fine.这一切都很好。 What I am failing to achieve is the following: When the image is clicked it becomes obsolete so I want to replace the clickable image with a new, unclickable image.我未能实现的是:单击图像时,它变得过时了,所以我想用一个新的、不可点击的图像替换可点击的图像。 I have tried using the array.splice method as follows newArray=myImages.splice(evt.target,1,newImage) This places the new image at position 0 in the new array and not in its original position and no new image is produced to overwrite the older image.我尝试使用 array.splice 方法如下 newArray=myImages.splice(evt.target,1,newImage) 这将新图像放置在新数组中的 position 0 而不是其原始 position 中,并且不会生成新图像覆盖旧图像。 I would be grateful for any help.如果有任何帮助,我将不胜感激。

If we guess that evt in newArray=myImages.splice(evt.target,1,newImage) is an Event object, evt.target is a DOM element , not an index.如果我们猜测newArray=myImages.splice(evt.target,1,newImage)中的evt是一个事件 object, evt.target是一个DOM 元素,而不是索引。 If this is in the click event you describe, it will be the clicked image.如果这是在您描述的点击事件中,它将是点击的图像。

The first argument of splice is the index at which to make changes; splice的第一个参数是进行更改的索引; a number.一个号码。 DOM elements are not numbers. DOM 元素不是数字。

splice also returns an array of deleted images, not an updated array. splice还返回一个已删除图像的数组,而不是更新的数组。 (Unlike methods like map or slice , splice modifies the array you call it on.) (与mapslice等方法不同, splice会修改您调用它的数组。)

You can find the previous image's index by using indexOf and then us splice with that:您可以使用indexOf找到上一张图像的索引,然后我们将其splice

const index = myImages.indexOf(evt.target);
if (index !== -1) {
    myImages.splice(index, 1, newImage);
}

or you could use map to create a new array with the new image in place of the clicked one:或者您可以使用map创建一个新数组,其中包含新图像来代替单击的图像:

newArray = myImages.map(img => img === evt.target ? newImage : img);

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

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