按钮仅显示一次图像

button showing image only once?

本文关键字:一次 图像 显示 按钮      更新时间:2023-09-26

快速提问,

我是一个完整的JS菜鸟,所以我很难在互联网上找到正确答案。所以我想我会在这里问我的问题。

我写了这两个函数。

<script language="javascript" type="text/javascript">
function test() {
show_image("nummer/test.jpg", 120,160, "Firstname Lastname");
show_image("nummer/test2.jpg", 120,160, "Firstname2 Lastname2");
}
function show_image(src, width, height, alt) {
    var img = document.createElement("img");
    img.src = src;
    img.width = width;
    img.height = height;
    img.alt = alt;
    document.body.appendChild(img);
}
//edited piece of code:
function removeImages(){
            var images = document.getElementsByTagName("img");
            for (index = images.length - 1; index >= 0; index--) {
                images[index].parentNode.removeChild(images[index]);
            }
        }
</script>
<button onclick="test();">test</button>

这将完美地显示图像,但是当您继续单击按钮时,它会不断生成图像。因此,如果您继续单击该按钮,我的页面会充满相同的图像。

我需要一种方法来限制这种情况。我想在第二次单击按钮或单击另一个按钮时使图像再次消失。

谢谢!

编辑:

找到了我最初问题的解决方案,现在使用额外的功能编辑块代码以替换图像。我知道我的代码确实效率不高,但它有效。

在 OP 注释澄清后编辑。想想你的show_image逻辑在做什么。您正在创建一个图像,并在每次单击按钮时附加它

现在,你真正想做什么?回答这个问题,你就有了答案。让我们创建一个故事:每次单击按钮时,如果屏幕上没有我的两个图像,我想添加它们,或者如果它们在屏幕上,则删除它们。

有很多方法可以做到这一点。如果您只想在视觉上隐藏它们,您可以使用 CSS,您可以销毁和创建新图像,您可以附加/分离相同的图像等。但有一件事保持不变:您需要跟踪您正在创建的图像是否已创建。(这也有多种方法;你可以查询 dom,你可以存储对项目的引用,你可以使用布尔开关等)。

下面是一个实时示例,它使用原始代码作为基础,但仅跟踪我们创建一次的图像引用,并通过每次单击按钮将其从 dom 中附加或删除:

// Define our images in the outer closure.
var img1, img2;
// Handle the button click
function toggleImages() {
  // If we haven't created our images, create and store them in
  // our variables.
  if (!img1) {
    img1 = create_image('http://lorempixel.com/120/160?a', 120, 160, "Firstname Lastname");
  }
  if (!img2) {
    img2 = create_image('http://lorempixel.com/120/160?b', 120, 160, "Firstname Lastname");
  }
  // Toggle our images
  toggle_image(img1);
  toggle_image(img2);
}
function create_image(src, width, height, alt) {
  var img = document.createElement('img');
  img.src = src;
  img.width = width;
  img.height = height;
  img.alt = alt;
  return img;
}
function toggle_image(img) {
  var parent = img.parentElement;
  // If our images are not attached to a parent, attach them.
  // Otherwise, remove them.
  if (!parent) {
    document.body.appendChild(img);
  } else {
    parent.removeChild(img);
  }
}
<button onclick="toggleImages()">Toggle some images!</button><br><br>

我没有

时间测试运行它,但我希望这可以解决您的问题:

注意我正在选择已创建的 img 并在附加另一个之前将其删除

function test() {
var x = document.querySelector('img');
var body = document.querySelector('body');
if(x){ // if an img has been found do that
   body.removeChild(x);
}
show_image("nummer/test.jpg", 120,160, "Firstname Lastname");
show_image("nummer/test2.jpg", 120,160, "Firstname2 Lastname2");
}
function show_image(src, width, height, alt) {
    var img = document.createElement("img");
    img.src = src;
    img.width = width;
    img.height = height;
    img.alt = alt;
    document.body.appendChild(img);
}

因为你说"当另一个按钮被点击时",我假设你正在尝试制作它,所以有多个按钮,每个按钮加载不同的图像。

如果确实如此,我会采用以下方法:

// Array of image objects to keep things neat
var images = [
    { "src": "http://placehold.it/120x160", "width": "120", "height": "160", "alt": "Test Image 1" },
    { "src": "http://placehold.it/120x161", "width": "120", "height": "160", "alt": "Test Image 2" }
];
function show_image(image) {
    // Ensure provided index is in array
    if (image < images.length) {
        // Remove this image if already displayed
        if (document.getElementsByClassName("imageNo" + image)[0] !== undefined)
            document.getElementsByClassName("imageNo" + image)[0].outerHTML = "";
        else {
            // Remove other images if displayed
            if (document.getElementById("currentImage") !== null) 
                document.getElementById("currentImage").outerHTML = "";
            var img = document.createElement("img");
            var cur = images[image];
            img.id = "currentImage";
            img.className = "imageNo" + image;
            img.src = cur.src;
            img.width = cur.width;
            img.height = cur.height;
            img.alt = cur.alt;
            document.body.appendChild(img);
        }
    }
    else 
        console.log('No image exists for this index');
}
// Add functionality to buttons
document.getElementById("imageButton1").onclick = function() {show_image(0);}
document.getElementById("imageButton2").onclick = function() {show_image(1);}

小提琴

如果您有一个按钮想要循环浏览所有图像,则可以使用相同的方法,但show_image更改为

var currentImage = 0;
function show_image() {
    // Remove other images if displayed
    if (document.getElementById("currentImage") !== null) 
        document.getElementById("currentImage").outerHTML = "";
    var img = document.createElement("img");
    var cur = images[currentImage++ % images.length];
    img.id = "currentImage";
    img.src = cur.src;
    img.width = cur.width;
    img.height = cur.height;
    img.alt = cur.alt;
    document.body.appendChild(img);
}
function hide_image() {
    // Remove other images if displayed
    if (document.getElementById("currentImage") !== null) 
        document.getElementById("currentImage").outerHTML = "";
    currentImage = 0;
}
// Add functionality to buttons
document.getElementById("imageButton1").onclick = function() {show_image();}
document.getElementById("imageButton2").onclick = function() {hide_image();}

小提琴

希望其中之一是您正在寻找的。

编辑:

对于多维数组,您需要执行以下操作:

// Array of image objects to keep things neat
var images = [
    //group 1
    [
        { "src": "http://placehold.it/120x160", "width": "120", "height": "160", "alt": "Test Image 1" },
        { "src": "http://placehold.it/120x161", "width": "120", "height": "160", "alt": "Test Image 2" }
    ],
    //group 2
    [
        { "src": "http://placehold.it/120x160", "width": "120", "height": "160", "alt": "Test Image 3" },
        { "src": "http://placehold.it/120x161", "width": "120", "height": "160", "alt": "Test Image 4" }
    ],
];

显然,如果您要拥有800张图像,这将更加乏味。 所有图像的宽度/高度都相同吗? 如果是这样,我会在SEO上受到打击,去做这样的事情:

var imageUrls = [
    "http://placehold.it/120x160",  
    "http://placehold.it/120x160", 
    //etc.
];
    // Change this as desired
var itemsPerGroup = 40;
// Returns how many times imageUrls length can be divided into 40 for group count
var images = new Array(Math.floor(imageUrls.length/itemsPerGroup) + 1);
// Initializes child arrays, ensuring last is only as long as it needs to be
for (var i=0; i<images.length; i++)
    images[i] = (i !== images.length - 1) ? new Array(itemsPerGroup) : new Array(images.length % itemsPerGroup);
// Fill arrays
for (var i=0; i<imageUrls.length; i++) {
    // current group
    var group = Math.floor(i/itemsPerGroup);
    // dividend is item number
    var item = i%itemsPerGroup;
    images[group][item] = {
        "src": imageUrls[i],
        "alt": "Group " + group + ", Image " + item,
        "width": "120",
        "height": "160"
    };
}

使用它,您将像这样调用图像

// Array of currentImages
var currentImages = new Array(images.length);
// Initialize
for (var i=0; i<currentImages.length; i++)
    currentImages[i] = 0;
function show_image(group) {
    var imageID = "currentImage" + group;
    var imageContainer = "imageGroup" + group + "Container";
    // Remove other image in group if displayed
    if (document.getElementById(imageID) !== null) 
        document.getElementById(imageID).outerHTML = "";
    var img = document.createElement("img");
    var cur = images[group][currentImages[group]++%images[group].length];
    img.id = "currentImage" + group;
    img.src = cur.src;
    img.width = cur.width;
    img.height = cur.height;
    img.alt = cur.alt;
    document.getElementById(imageContainer).appendChild(img);
}
function hide_image(group) {
    // Remove image in group if displayed
    var imageID = "currentImage" + group;
    if (document.getElementById(imageID) !== null) 
        document.getElementById(imageID).outerHTML = "";
    // Reset currentImage
    currentImages[group] = 0;
}

当然,还有一把小提琴在行动中展示它。