다음 코드는 설명이 필요하지만 생성 된 요소에 click 이벤트를 바인딩하는 문제가 있습니다.동적으로 생성 된 요소를 jQuery에서 바인딩
25 행에서 'overlay'ID를 가진 div를 생성하고 있습니다. 그런 다음 CSS 속성을 설정합니다.
그런 다음 65 행에서 클릭하여 모달 숨기기를 트리거합니다. 문제는 작동하지 않는다는 것입니다. div에 html을 넣으면 .click이 예상대로 작동합니다.
도움을 주시면 감사하겠습니다. #overlay 요소가 존재하지 않는 경우
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Modal</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// Select the link(s) with name=modal
$('a[name=modal]').click(function(e) {
// Cancel the link behavior
e.preventDefault();
// Get the id of this link's associated content box.
var id = $(this).attr('href');
// Find the screen height and width
var overlayHeight = $(document).height();
var overlayWidth = $(window).width();
// Create the overlay
$('body').append('<div id="overlay"></div>');
//Set css properties for newly created #overlay
$('#overlay').css({
'width' : overlayWidth,
'height' : overlayHeight,
'position':'absolute',
'left' : '0',
'top' : '0',
'z-index' : '9000',
'background-color' : '#000',
'display' : 'none'
});
// Get the viewpane height and width
var winH = $(window).height();
var winW = $(window).width();
// Center the modal
$(id).css('top', winH/2-$(id).height()/2);
$(id).css('left', winW/2-$(id).width()/2);
// Transition effects for overlay
$('#overlay').fadeIn(1000).fadeTo(1000,0.8);
// Transition effect for modal
$(id).fadeIn(1000);
});
// Close link click = trigger out
$('.modal .close').click(function (e) {
//Cancel the link behavior
e.preventDefault();
$('#overlay').fadeOut(1000);
$('.modal').fadeOut(200);
});
// Overlay click = trigger out
$('#overlay').click(function() {
$('#overlay').fadeOut(1000);
$('.modal').fadeOut(200);
});
// Load rules in to modal
$('#rules .text').load('rules.html');
});
</script>
<style type="text/css">
.modal{
position:absolute;
display:none;
z-index:9999;
}
#rules{
width:600px;
height:400px;
}
#rules p{
background: #fff;
margin: 0;
padding: 0;
}
#rules .head{
background: #ddd;
text-align: right;
padding: 0 10px;
height: 30px;
}
#rules .text{
height: 370px;
padding: 0 20px;
overflow: auto;
}
</style>
</head>
<body>
<p><a href="#rules" name="modal">Open Modal</a></p>
<div id="rules" class="modal">
<p class="head"><a href="#" class="close">close</a></p>
<p class="text"></p>
</div>
</body>
</html>
+1 스택 오버플로에 오신 것을 환영합니다. @ Greg-J! – Sampson