我需要为 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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句