javascript - yacal.js next/back button removes jquery event listener -
i using yacal.js build calendar.
here javascript , css yacal.js (its site because couldn't find cdn it)
for project, trying make when user clicks on date, ajax request sent php page date , php page gets row database matching date.
all of works fine... when click next/back button (the 2 buttons @ top of calendar change months) removes jquery event:
$("a.day").click(function() {
why happening?
or can fix it?
<!doctype html> <html> <head> <title>calendar</title> <!-- latest compiled , 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 < 10) ? '0' + : a; b = (b < 10) ? '0' + b : b; alert('day:' + + ', month:' + b + ', year:' + c); } $('#calendartemplate').yacal(); </script> </body> </html>
notice after click or forward buttons few times doesn't alert anymore
use event delegation
event delegation allows attach single event listener, parent element, fire descendants matching selector, whether descendants exist or added in future.
you're binding event on page load. when elements removed , replaced other elements(days), event unbound.
bind event using on
as
$("#calendartemplate").on("click", "a.day", function() {
demo
$(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 < 10) ? '0' + : a; b = (b < 10) ? '0' + b : b; alert('day:' + + ', 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>
Comments
Post a Comment