You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

技术问题:无法将currentIndex更新为选中模态框打开时的对应索引

问题描述

我实现了一个用于打开图库的ModalManager类,当前存在一个问题:点击图库中的图片打开模态框时,currentIndex无法更新为该图片对应的索引,每次打开模态框都默认从索引0开始展示,只有点击上一张/下一张按钮时,索引才能正常切换。

以下是完整的代码片段:

class ModalManager {
  #modals;
  #currentIndex;
  #myModalDialog;

  constructor(
    modalSelector,
    catalogSelector
  ) {
    this.#modals = document.querySelectorAll(modalSelector);
    this.#currentIndex = 0;
    this.#myModalDialog = document.querySelector("#modal-dial");
    this.#bindCatalogClick(catalogSelector);
    this.#bindModalClick();
  }

  #openModal(index, direction) {
    this.#modals.forEach((modal, i) => {
      modal.style.display = i === index ? "block" : "none";
      modal.classList.remove("animate-left", "animate-right");
      if (i === index) {
        const animationClass =
          direction === "left" ? "animate-left" : "animate-right";
        modal.classList.add(animationClass);
      }
    });
    this.#currentIndex = index;
    console.log(index);
  }


  #bindCatalogClick(catalogSelector) {
    document
      .querySelector(catalogSelector)
      .addEventListener("click", ({ target }) => {
        if (!target.matches("img[data-modal]")) return;
        this.#myModalDialog.className = target.dataset.modal;
        this.#myModalDialog.classList.add("modal-fade-in");
        console.log(this.#currentIndex);
        setTimeout(
          () => this.#myModalDialog.classList.remove("modal-fade-in"),
          500
        );
        this.#myModalDialog.showModal();
      });
  }
}

const modalManager = new ModalManager(
  ".gallery",
  "#next-img",
  "#prev-img",
  ".catalog__wrapper"
);
解决方案

我已经解决了这个问题,核心原因是点击图库图片时没有调用#openModal方法,导致currentIndex始终停留在初始的0值。

修复步骤:

  1. 确保图库中的每张图片元素都带有存储索引的属性(比如data-index),例如:<img data-modal="xxx" data-index="2" ...>
  2. 在#bindCatalogClick的点击事件处理函数中,获取点击图片的索引值并转换为数字,然后调用#openModal方法更新索引:

修改后的#bindCatalogClick方法如下:

#bindCatalogClick(catalogSelector) {
  document
    .querySelector(catalogSelector)
    .addEventListener("click", ({ target }) => {
      if (!target.matches("img[data-modal]")) return;
      // 获取并转换点击图片的索引
      const targetIndex = parseInt(target.dataset.index, 10);
      this.#myModalDialog.className = target.dataset.modal;
      this.#myModalDialog.classList.add("modal-fade-in");
      // 调用openModal更新当前索引并展示对应图片
      this.#openModal(targetIndex, "right");
      setTimeout(
        () => this.#myModalDialog.classList.remove("modal-fade-in"),
        500
      );
      this.#myModalDialog.showModal();
    });
}

这样点击图库中的任意图片时,currentIndex就会被正确设置为该图片的索引,模态框也会直接展示对应的图片。

内容的提问来源于stack exchange,提问作者user25737164

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 23:00:11