按钮只显示一次图像?

时间:2015-03-13 18:38:09

标签: javascript image button undo-redo

快速提问,

我是一个完整的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>

这样可以很好地显示图像,但是当您一直单击按钮时,它会一直生成图像。因此,如果您继续单击该按钮,我的页面将填充相同的图像。

我需要一种方法来限制它。当第二次点击按钮或点击另一个按钮时,我想让图像再次消失。

谢谢!

编辑:

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

3 个答案:

答案 0 :(得分:1)

在OP评论澄清后编辑。考虑一下show_image逻辑正在做什么。您创建图像并在每次单击按钮时附加图像

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

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

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

&#13;
&#13;
// 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);
  }
}
&#13;
<button onclick="toggleImages()">Toggle some images!</button><br><br>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我没有时间测试它,但我希望能解决你的问题:

注意我正在选择已创建的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);
}

答案 2 :(得分:0)

因为你说&#34;当点击另一个按钮&#34;时,我假设你正试图这样做,所以有多个按钮,每个按钮加载不同的图像。

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

// 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);}

Fiddle

如果您有一个按钮,您想循环浏览所有图像,您可以使用相同的方法,但将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();}

Fiddle

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

修改

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

// 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张照片,这将会更加乏味。所有图像的宽度/高度是否相同?如果他们是,我会采取搜索引擎优化的目标去寻找类似的东西:

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;
}

And of course, a Fiddle showing it in action.