javascript - jquery监听动态创建元素上的点击事件

标签 javascript jquery event-handling event-delegation

我需要为 html 页面创建一个模式。单击页面上的按钮时,会显示模态框。关闭模态的按钮包含在模态本身中。

问题是关闭按钮上的单击事件(该事件意味着从文档中删除模态 html)不起作用。但是,分配给同一事件的 console.log 会显示在控制台中。为什么会发生这种情况以及如何解决它?

笔:https://codepen.io/t411tocreate/pen/prZRYN

JS代码:

$(document).ready(function(){
  $('#showModal').on('click', function() {
    $('.container').append(modalHtml)
  })

  $(document).on('click','#closeModal',function(){
    console.log('click triggered')
    $(document).remove('#modal')
 })

  var modalHtml = '<div id="modal"> <div class="modal-bg"></div><div class="modal-content"> <p>this is a modal</p><span id="closeModal">close</span> </div></div>'
})

最佳答案

直接在元素上调用 remove() - 使用 $('#modal').remove() 代替 - 请参阅下面的演示:

$(document).ready(function() {
  $('#showModal').on('click', function() {
    $('.container').append(modalHtml)
  })

  $(document).on('click', '#closeModal', function() {
    $('#modal').remove();
  })

  var modalHtml = '<div id="modal"> <div class="modal-bg"></div><div class="modal-content"> <p>this is a modal</p><span id="closeModal">close</span> </div></div>'
})
#showModal {
  margin: 50px 40%;
  font-size: 50px;
}

#modal {
  display: block;
}

#modal .modal-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

#modal .modal-bg:before {
  content: "";
  display: block;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  background-color: rgba(43, 43, 43, 0.5);
}

#modal .modal-content {
  width: 50%;
  margin: 20px auto;
  position: relative;
  background: black;
  color: #fff;
  padding: 20px;
}

#modal .modal-content #closeModal {
  padding: 10px;
  margin: 10px;
  border: 1px solid #fff;
}

#modal .modal-content #closeModal:hover {
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <button id="showModal"> Show modal</button>
</div>

关于javascript - jquery监听动态创建元素上的点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45865669/

相关文章:

javascript - 异步过滤 Promise 数组

Javascript fadeIn fadeOut 不断重新淡出(没有 JQuery!)

jquery - 动画半饼图

javascript - 如何让 JqueryUI Sortable 与缩放/缩放一起工作 - 鼠标移动

java - 实例变量的值在两个类中是不同的。为什么? (+更多问题)

javascript - 事件发射器,对象不是函数

c# - 检查控件是否在 Click EventHandler 上有事件

javascript - 使用 jquery 将值设置为隐藏列

javascript - 如何使用没有位置 : fixed? 的页面滚动 div

javascript - 我收到错误 : Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script