简体   繁体   English

如何在 Javascript 中添加关闭按钮或清除代码?

[英]How to add a close button or clear code in Javascript?

I have a gallery of pictures (dynamically fetched from a json).我有一个图片库(从 json 动态获取)。 When I open the link, picture pops up, but I am not able to close it.当我打开链接时,图片弹出,但我无法关闭它。

I would need either to add some kind of "Close button" or just to clear the code (onclick event?).我需要添加某种“关闭按钮”或只是清除代码(onclick 事件?)。

createImg.setAttribute("src", books[i].cover)
createImg.setAttribute("alt", "Avatar")
createImg.setAttribute("style", "width:290px;height:380px;")

 var createButton = document.createElement("button");
createButton.setAttribute("type", "button");
createButton.setAttribute("id", books[i].detail);
createButton.addEventListener("click", function (event) {
  var showPicture = document.getElementById("showPictureID")

// - clean code or close button (on click ??)

  var createDet = document.createElement('img');
     createDet.setAttribute("src", event.target.id)
  createDet.setAttribute("alt", "image")
  createDet.setAttribute("style", "position:fixed;top:20%;left:20%;")

  var showPicture = document.getElementById("showPictureID")
  showPicture.appendChild(createDet);

Not sure how to approach this.不知道如何处理这个。 Its a long code, thus I'm pasting just a part of it... Up we have fetching这是一个很长的代码,因此我只是粘贴其中的一部分......我们正在获取

Any ideas are very appreciated.任何想法都非常感谢。

Just before creating img element "createDet" you can create button element for deleting就在创建 img 元素“createDet”之前,您可以创建用于删除的按钮元素

var closeBtn = document.createElement('button');
closeBtn.innerHTML = "Close image";
showPicture.appendChild(closeBtn);

closeBtn.addEventListener ("click", function() {
    var showPicture = document.getElementById("showPictureID");
    var imgTag = showPicture.getElementsByTagName('img')[0]; //or use more precise selection for image that must be closed
    showPicture.removeChild(imgTag);

    var btnTag = showPicture.getElementsByTagName('button')[0]; //remove the close button too
    showPicture.removeChild(btnTag);
});

Style the button with css as you wish.根据需要使用 css 设置按钮样式。

If showPicture contains only the picture, you can just empty it, but you should use only one of event listeners not both.如果 showPicture 只包含图片,您可以清空它,但您应该只使用一个事件侦听器,而不是同时使用两者。

closeBtn.addEventListener ("click", function() {
    var showPicture = document.getElementById("showPictureID");
    showPicture.innerHTML = '';
});

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

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