简体   繁体   中英

jquery function call on page both onload and onclick?

i am working on jquery calender but i need to call a function both on page load and then on click. when the page load for the first time it should automatically call and execute the function and for 2nd time and onward it should be call through click. is it possible?? if yes please help me.

   <script type="text/javascript">

   $(document).ready(function(){
      $("#fullDate").datepicker({

        showOn: "button",
        buttonImage: "images/calender.jpg",
        buttonImageOnly: true,

        onClose: function(dateText, inst) {
        $('#year').val(dateText.split('/')[2]);
        $('#month').val(dateText.split('/')[0]);
        $('#day').val(dateText.split('/')[1]);
    }


    });


});
</script>

Try writing a named function and call it on both events:

function doSomething() {
    // ...
}
$(document).ready(function() { doSomething() });
$(yourElem).on("click", function() { doSomething() });

Alternatively to writing an anonymous function as a callback, just to call doSomething , you could also pass the function name as an argument, gaining a little performance by not cluttering memory with unnecessary anonymous functions:

$(document).ready(doSomething);
$(yourElem).on("click", doSomething);
$(document).ready(function(){
  $("#fullDate").datepicker({
    showOn: "button",
    buttonImage: "images/calender.jpg",
    buttonImageOnly: true,

    onClose: function(dateText, inst) {
        $('#year').val(dateText.split('/')[2]);
        $('#month').val(dateText.split('/')[0]);
        $('#day').val(dateText.split('/')[1]);
    }
  });
  $("#fullDate").datepicker("show"); // this will run once.
});

During load, you can use

//when window loads
$(window).load(function(){
    functionCallHere();
});

//or when DOM is ready
$(document).ready(function(){
    functionCallHere();
});

Then for the click

$(element).click(function(){
    functionCallHere();  //call the function again
});

Where functionCallHere is the name of the common function called on those events.

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