javascript - 有谁知道为什么这段代码不能按我想要的方式工作?
问题描述
我正在使用 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),我无法弄清楚为什么什么都没有发生,希望任何人都可以帮助我。
谢谢马特乌斯
解决方案
使用时,.parentElement.removeChild()
您已关闭这些按钮的所有事件侦听器。
你有两个选择。您可以通过存储.removeChild()
调用的返回值来保留事件侦听器。为了恢复事件侦听器,您需要重用存储的(以前删除的)节点。
或者,您需要在插入新 HTML 后重新添加事件侦听器。
推荐阅读
- r - 在多个列上计算多个 Pareto 图
- latex - 如何将 LaTeX 项目转换为破折号
- jquery - 多个预览图像和删除
- python - 使用池类在 Python 中进行多处理
- node.js - 如何在 Azure IOT 集线器中激活 X509 自分配设备类型的设备?
- mongodb - 如何按每小时对数据进行分组
- font-awesome - 在具有不同图标样式的 Openlayers 中使用 Fontawesome
- python - 一维数组到RGB图像?
- android - android中按钮上的java.lang.NullPointerException
- java - 在 maven 中使用/导入本地 fat jar 作为插件