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

q3qa4bjr  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(268)

所以我构建了一个小的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);
}
w8rqjzmb

w8rqjzmb1#

为了以防万一,若您需要在双击时删除图像,可以使用jquery双击事件。

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

agyaoht72#

// 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")

相关问题