我正在使用yacal.js来制作日历。
以下是yacal.js的javascript和css(来自我的网站,因为我无法找到cdn)
对于我的项目,我试图让它成为当用户点击日期时,ajax请求被发送到我的php页面,日期和我的php页面从匹配日期的数据库中获取一行。
所有这些工作正常......但是当我点击下一个/后退按钮(日历顶部的两个按钮会改变几个月)时,它会删除我的jQuery事件:
$("a.day").click(function() {
为什么会这样?
或我该怎么办才能修复它?
<!DOCTYPE html>
<html>
<head>
<title>Calendar</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="http://wxrunning.com/tests/jquery.yacal.css">
</head>
<body>
<div id="calendarTemplate"></div>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js" type="text/javascript"></script>
<script src="http://wxrunning.com/tests/jquery.yacal.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("a.day").click(function() {
showData(
Number($(this).html()),
$(this).parents("div.month").attr('class').replace('month m', ''),
$(this).parents("div.month").children('h4').html().replace(/\D/g, '')
);
});
});
function showData(a, b, c) {
a = (a < 10) ? '0' + a : a;
b = (b < 10) ? '0' + b : b;
alert('Day:' + a + ', Month:' + b + ', Year:' + c);
}
$('#calendarTemplate').yacal();
</script>
</body>
</html>
&#13;
请注意,在您单击后退或前进按钮几次后,它不会再发出警报
答案 0 :(得分:2)
事件委托允许我们将单个事件侦听器附加到父元素,该元素将为匹配选择器的所有后代触发,无论这些后代现在是存在还是将来添加。
您在页面加载时绑定事件。但是当元素被删除并被其他元素(天)替换时,该事件是未绑定的。
使用on
$("#calendarTemplate").on("click", "a.day", function() {
<强>演示强>
$(document).ready(function() {
$("#calendarTemplate").on("click", "a.day", function() {
showData(
Number($(this).html()),
$(this).parents("div.month").attr('class').replace('month m', ''),
$(this).parents("div.month").children('h4').html().replace(/\D/g, '')
);
});
});
function showData(a, b, c) {
a = (a < 10) ? '0' + a : a;
b = (b < 10) ? '0' + b : b;
alert('Day:' + a + ', Month:' + b + ', Year:' + c);
}
$('#calendarTemplate').yacal();
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="http://wxrunning.com/tests/jquery.yacal.css">
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js" type="text/javascript"></script>
<script src="http://wxrunning.com/tests/jquery.yacal.min.js" type="text/javascript"></script>
<div id="calendarTemplate"></div>