事件委托-错误类的事件触发器

时间:2018-09-16 18:51:27

标签: javascript event-delegation

我正在尝试使用html-vanilla javascript创建一个滑块。我能够打开模态,显示宽滑块图像和小图像(缩略图)。一切看起来都很好,但是当我单击缩略图(具有“ small_image”类)时,它们会触发事件,更改图像并将相同的图像再次添加到缩略图部分。

当我单击任何缩略图时,我用console.log(e.target.className)检查了控制台,它显示的是“ slider”类而不是“ small_image”类。为什么会这样,我该如何解决?

HTML部分

<div id="photos" class="tabcontent">
    <div class="tabslider">
        <div>
            <img src="{{image_path("posts/5-1537128615.jpg")}}" class="slider">
        </div>
        <div>
            <img src="{{image_path("posts/6-1537128615.jpg")}}" class="slider">
        </div>
        <div>
            <img src="{{image_path("posts/7-1537128615.jpg")}}" class="slider">
        </div>
        <div>
            <img src="{{image_path("posts/8-1537128615.jpg")}}" class="slider">
        </div>
        <div id="myModal" class="modal">
            <span class="close cursor">&times;</span>
            <div class="modal-content">
              <!-- wide image -->
                <div class="mySlides">
                    <img class="show_slider" src="">
                </div>
              <!-- small images -->
                <div class="small_images"></div>

            </div>
        </div>
    </div>

</div>

JavaScript部分

document.querySelector(".tabslider").addEventListener("click", function (e) {
    if (e.target.className = "slider") {
        let smallImages = document.querySelector(".small_images"),
            images = document.querySelectorAll(".slider"),
            slider = document.querySelector(".show_slider"),
            sliderDiv = document.querySelector(".mySlides"),
            model = document.querySelector("#myModal");

        model.style.display = "block";

        images.forEach(function (image) {
            let img = Elementor.create("img", {"src": image.src, "class": "small_image"}),
                div = Elementor.create("div", {"class": "columnlightbox"},);
            div.appendChild(img);
            smallImages.appendChild(div);
        });

        slider.setAttribute("src", e.target.src);
        sliderDiv.style.display = "block";
    }
})

1 个答案:

答案 0 :(得分:1)

e.target.className = "slider"

您正在此处设置值,而不是比较:D