首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Javascript事件侦听器没有按预期作出反应-有些事件没有触发

Javascript事件侦听器没有按预期作出反应-有些事件没有触发
EN

Stack Overflow用户
提问于 2021-10-10 11:07:23
回答 2查看 144关注 0票数 1

我有下面这个简单的页面。

代码语言:javascript
复制
<style>
    #notifier {
        position: fixed;
        width: 320px;
        bottom: 0;
        left: 0;
        padding: 10px;
    }

    #notification-silo {
        width: 300px;
        height: 100%;
        position: relative;
    }

        #notification-silo .notification {
            position: absolute;
            bottom: 0;
            width: 300px;
            background-color: #fff;
            box-shadow: 2px 2px 8px 2px #666;
        }

        #notification-silo .header {
            background-color: #1266AB;
            color: #fff;
            padding: 5px;
        }

        #notification-silo .error .header {
            background-color: #1266AB;
        }

        #notification-silo .warning .header {
            background-color: #ff8f5f;
        }

        #notification-silo .header .title {
            width: 260px;
            display: inline-block;
        }

        #notification-silo .header .close-wrapper {
            display: inline-block;
        }

            #notification-silo .header .close-wrapper button {
                height: 25px;
                width: 25px;
                background-color: #2277bb;
                border: 0;
                color: #ff8f5f;
                border-radius: 50%;
            }

        #notification-silo .warning .header .close-wrapper button {
            background-color: #ffaa77;
            color: #2277bb;
        }

    #notifier .body {
        padding: 5px;
        border: 1px solid lightgray;
    }
</style>

<div id="notifier">
    <div id="notification-silo">
    </div>
</div>

<script>
    function show(html) {
        let notification, notificationArray, body, closeButton, existingNotificationHeights, sum, bottom, notification_template, siloElement, marginBetweenNotifications;

        siloElement = document.querySelector("#notification-silo");
        notification_template = `<div class="notification">
                                    <div class="header">
                                        <div class="title">Message</div>
                                        <div class="close-wrapper">
                                            <button>X</button>
                                        </div>
                                    </div>
                                    <div class="body"></div>
                                </div>`;
        marginBetweenNotifications = 10;

        // calculate position
        existingNotificationHeights = [...siloElement.children].map(notification => notification.offsetHeight);
        sum = existingNotificationHeights.length ? existingNotificationHeights.reduce((a, b) => a + b) : 0;
        bottom = sum + existingNotificationHeights.length * marginBetweenNotifications;

        // creat elements by update innerHTML
        siloElement.innerHTML += notification_template.trim();
        notificationArray = [...siloElement.querySelectorAll(".notification")];
        notification = notificationArray[notificationArray.length - 1];
        notification.style.bottom = bottom + "px";
        body = notification.querySelector(".body");
        body.innerHTML += html;

        // add event listener to close button
        closeButton = notification.querySelector(".close-wrapper button");
        closeButton.addEventListener("click", (ev) => {
            console.log("click is fired");
        });
    };
    
    show("System message 1");
    show("System message 2");
    show("System message 3");
    show("System message 4");
    show("System message 5");
</script>

它意味着通过show(msg)函数创建简单的通知消息。下面是有趣的部分--当创建少量消息并尝试将事件侦听器添加到它们的关闭按钮时,只有最后一个按钮获得一个侦听器并真正侦听单击事件。所有其他关闭按钮都不会对鼠标单击作出反应。你能帮我理解一下原因吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-10-10 12:07:16

引用ProGu:

--我猜siloElement.innerHTML += notification_template.trim()删除了html内容,并重新分配了一次,因此删除了以前的事件.

票数 0
EN

Stack Overflow用户

发布于 2021-10-10 11:17:56

只有你必须得到关闭按钮引用对象

代码语言:javascript
复制
    show("System message 1");
    show("System message 2");
    show("System message 3");
    show("System message 4");
    show("System message 5");

[].forEach.call(document.querySelectorAll("#notification-silo button.close-wrapper"),function(el){
      el.addEventListener("click",function(ev){
            var targetElement = ev.target || ev.srcElement;
            console.log(targetElement); //reference of button... 
      });
    });

代码语言:javascript
复制
<div class="close-wrapper">
     <button onClick="Close(this)">X</button>
</div>

或者完美如一种标准方式不使用静态html模板字符串使用动态纯JavaScript元素创建方法

例子:

代码语言:javascript
复制
let mainDiv = document.querySelector("#notification-silo");
let aTag = document.createElement('a');
aTag.innerHTML = "CLOSE TEXT....";
aTag.addEventListener("click", (ev) => {
        console.log("click is fired");
});
mainDiv.appendChild(aTag);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69514591

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档