【问题标题】:Javascript pop up on multiple elementsJavascript 在多个元素上弹出
【发布时间】:2022-01-23 11:20:40
【问题描述】:

我正在尝试构建一个用 JavaScript 编写的弹出函数,但我觉得代码可能会更好。

所以我有两个缩略图,点击它会显示相应的图像但更大。

我想用大约 20 个这样的代码构建一个页面,但我觉得会有很多代码重复,我被卡住了。

我的代码在这里:

https://codesandbox.io/s/i8b1s

这是我的 JS:

/*

The goal of this is to simplify the JS code as when I add more images
I do want to keep duplicating code. 


*/

// Tesing

const targetNum = document.querySelectorAll("target");
console.log(targetNum);

// Original code below
// Target 1
const target1 = document.querySelector(".counterNo1");
const target2 = document.querySelector(".counterNo2");

// Target 1 Pop Up
const target1MainImage = document.querySelector(".mainImage1");
const target2MainImage = document.querySelector(".mainImage2");

// Close buttons
const close1 = document.querySelector(".closeBTN1");
const close2 = document.querySelector(".closeBTN2");

//Target 1 Clicked Event
target1.addEventListener("click", function () {
  console.log("Target 1");
  target1MainImage.classList.remove("hide");
  target1MainImage.classList.add("show");
});
//Target 2 Clicked Event
target2.addEventListener("click", function () {
  console.log("Target 2");
  target2MainImage.classList.remove("hide");
  target2MainImage.classList.add("show");
});

// Close
//Close Event 1
close1.addEventListener("click", function () {
  console.log("Close Target 1");
  target1MainImage.classList.add("hide");
  target1MainImage.classList.remove("show");
});
//Close Event 2
close2.addEventListener("click", function () {
  console.log("Close Target 2");
  target2MainImage.classList.add("hide");
  target2MainImage.classList.remove("show");
});

如您所见,如果我有更多的弹出窗口,我正在复制事件侦听器等,并且我不希望元素有很多 dup 代码。这就是我卡住的地方。

谁能指出我该怎么做的正确方向?

谢谢,

本。

【问题讨论】:

  • 1.您需要一个 for 循环来将点击事件放在您的目标上。 2.你需要通过删除show类来关闭其他MainImages

标签: javascript popup


【解决方案1】:

所以你可以做的是创建一个通用的弹出窗口,让页面上有 20 个目标。所以你所要做的就是

// here create a variable to map the location or src value of bigger image

const ImageMapper = {
   one: '/images/one.jpg'
.....
}

// then create the function which calls the popup and set the src of the image element in it

const openPopup = (opener) => {
   popupImage.src = ImageMapper[opener]
   popup.classList.add('show')
}

// and in the poup add a button which closes the popup so that you dont have to write multiple functions just to close a single popup

const closePopup = () => {
    popup.classList.add('hide')
}

// and last in each of the possible element that will open the popup just add the onclick handler like

target1.onclick = () => {
    openPopup('one')
}

// this will require a lot less code then what you will have to write

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-02
    • 2017-01-30
    • 2014-01-16
    • 1970-01-01
    • 2013-02-28
    • 2014-06-27
    相关资源
    最近更新 更多