首页 > 解决方案 > 有谁知道为什么这段代码不能按我想要的方式工作?

问题描述

我正在使用 node.js、express 和 pug 模板创建一个 Web 应用程序,在这里我试图在用户尝试删除他发布的评论时模拟警告。

所以,在前端我有一个按钮,用户单击以删除他的评论

当用户单击该按钮时,我运行

index.js

import { showWarning } from './warning';

const removerStoreReviewBtn = document.querySelector('.side-nav__removeStoreReviewbtn');

if (removerStoreReviewBtn)
   removerStoreReviewBtn.addEventListener('click', e => {
      e.preventDefault();

      showWarning('Would you like to remove this review ?');
   });

警告.js

export const hideWarning = () => {
   const el = document.querySelector('.warning');
   const warningText = document.querySelector('.warning__text');
   if (el) el.parentElement.removeChild(el);
   if (warningText) warningText.parentElement.removeChild(warningText);
};

export const showWarning = (msg, time = 30) => {
   hideWarning();
   console.log(msg);
   const markUp = `
                        <div class="warning">
                            <div class="warning__text">${msg}</div>
                            <button class="warning--no">
                                <span>Cancelar</span>
                            </button>
                            <button class="warning--yes">
                                <span>Apagar</span>
                            </button>
                        </div>`;

   document.querySelector('.header').insertAdjacentHTML('afterend', markUp);
   window.setTimeout(hideWarning, time * 1000);
};

showWarning 函数在前端以我想要的方式显示所有内容

然后回到 index.js 文件,我有以下代码

index.js

const warningBtnYes = document.querySelector('.warning--yes');
const warningBtnNo = document.querySelector('.warning--no');

if (warningBtnYes)
   warningBtnYes.addEventListener('click', e => {
      e.preventDefault();
      console.log('remove');
      //removerStoreReview(reviewId);
   });
if (warningBtnNo)
   warningBtnNo.addEventListener('click', e => {
      e.preventDefault();
      console.log('Do not remove');
   });

当我单击这些按钮中的任何一个时,什么都没有发生(我期待 console.logs),我无法弄清楚为什么什么都没有发生,希望任何人都可以帮助我。

谢谢马特乌斯

标签: javascript

解决方案


使用时,.parentElement.removeChild()您已关闭这些按钮的所有事件侦听器。

你有两个选择。您可以通过存储.removeChild()调用的返回值来保留事件侦听器。为了恢复事件侦听器,您需要重用存储的(以前删除的)节点。

或者,您需要在插入新 HTML 后重新添加事件侦听器。

有用的文档


推荐阅读