jquery在动态创建的元素上侦听click事件

时间:2017-08-24 15:32:43

标签: javascript jquery event-handling event-delegation

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

问题是关闭按钮上的click事件,意味着从文档中删除模态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>'
})

4 个答案:

答案 0 :(得分:0)

您的问题是由于remove()中使用了选择器。那用作过滤器 - 不是为了找到元素。要修复逻辑,请直接选择元素并在其上调用remove()

$('#modal').remove();

Updated CodePen

答案 1 :(得分:0)

你这样做:

$(document).remove("#modal");

你应该这样做:

$("#modal").remove();

另请注意,您不需要等到DOM准备好将处理程序绑定到document

$(document).ready(function(){
   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').on('click', function() {
    $('.container').append(modalHtml)
  })
})

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

答案 2 :(得分:0)

直接在元素上调用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>

答案 3 :(得分:0)

替换

$(document).remove('#modal');

$('#modal').remove();