如何使已添加到 DOM 的 1 个 img 在双击时消失?

How to make only 1 img that has been added to the DOM disappear on double-click?

所以我构建了一个你们中的一些人可能熟悉的小型 DogAPI。我想让我的有点像拼贴画,但我想让人们可以选择双击图片并根据需要将其删除。到目前为止,我已经使用 JQuery 创建了图像并将它们附加到容器中。添加事件侦听器会使所有图像消失,因为它们都具有相同的 ID。实现这一目标超出了我的技能水平(初学者)。

https://codepen.io/drxl/pen/VwbQZyK

<div class="container">
<div class="header">
    <h1>Dog Collage!</h1>
    <p>Select a dog and create your collage!</p>
    <div id="breeds"></div>
</div>
<div class="slideshow" id="imgs">
</div>




   // fetches dog breed list/shows error if applicable
async function start() {
    try {
        const response = await fetch("https://dog.ceo/api/breeds/list/all")
        const data = await response.json()
        breedList(data.message)
    } catch (e) {
        console.log("There was a problem fetching the breed list.")
        alert("There was a problem fetching the breed list.")
    }
}


//load breed list in dropdown menu
start()
function breedList(dogList) {
    document.getElementById("breeds").innerHTML = `
    <select onchange="loadByBreed(this.value)">
        <option>Choose a dog breed</option>
        ${Object.keys(dogList).map(function (breed) {
        return `<option>${breed}</option>`
    }).join('')}
    </select>
    `
}

//load images
async function loadByBreed(breed) {
    if (breed != "Choose a dog breed") {
        const response = await fetch(`https://dog.ceo/api/breed/${breed}/images`)
        const data = await response.json()
        createImgs(data.message)
    }
}

//show randomized images
function createImgs(images) {
    let imageContainer = $(".slideshow");
    let dogImgs = $('<img>');
    dogImgs.attr("src", images[Math.floor(Math.random() * images.length)]);
    dogImgs.addClass(".dogPic")
    imageContainer.append(dogImgs);
}
// with jQuery you could just add a click listener to the class and remove the element, just add this below all your code
$(document).on('click', ".dogPic", function(){
    $(this).remove();
})

不过你需要先更正错别字:

dogImgs.addClass(".dogPic")

变成

dogImgs.addClass("dogPic")

如果您需要在双击时删除图像,您可以使用 jQuery 双击事件。

$(document).on('dblclick', ".dogPic", function(){
    $(this).remove();
});