简体   繁体   中英

onClick on fires once in self executing function jQuery

I'm using jQuery datepicker and need an self executing function for it to work properly so my JS looks like:

    $(function(){
        $('#datepicker').datepicker({
            // beforeShowDay: disableSpecificDays,
            inline: true,
            showOtherMonths: true,
            dayNamesMin: [ "M", "T", "W", "T", "F", "S", "S" ],
        });

        $('#datepicker td').on('click', function() {
            console.log($(this).text());
        });
    });

My onClick event works, but it only fires once. And if I take it out of the function it doesn't fire at all.

Does anyone know why?

Try using onSelect event :

$('#datepicker').datepicker({
     onSelect: function(dateText, inst) { 
        console.log(dateText);
         // you code here.. 
     }
 });

Called when the datepicker is selected. The function receives the selected date as text and the datepicker instance as parameters. this refers to the associated input field.

Or , You can simply re-attach your events to the ui-datepicker elements :

   var element = document.getElementById('datepicker'),
    cols = element.getElementsByTagName("td");

   attachEvents(); // call function on load

   function attachEvents() {
     for(var i = 0; i < cols.length; i++) {
         cols[i].addEventListener("click", function (ev) {
            console.log(this);
            attachEvents();
          }, false);
     }
    }

When you are attaching a click listener, the DOM element is not yet present. To overcome this problem, you need to use delegated event. Try using this code snippet:

$(function() {
    $('#datepicker').datepicker({
        // beforeShowDay: disableSpecificDays,
        inline: true,
        showOtherMonths: true,
        dayNamesMin: ["M", "T", "W", "T", "F", "S", "S"],
    });

    $('#datepicker').on('click', 'td', function() {
        console.log($(this).text());
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM