jQuery函数在页面上调用加载和点击

jquery function call on page both onload and onclick?

本文关键字:加载 调用 函数 jQuery      更新时间:2023-09-26

我正在研究jquery日历,但我需要在页面加载和点击时调用一个函数。 当页面首次加载时,它应该自动调用并执行该函数,并且第二次及以后应该通过单击调用。 可能吗?? 如果是,请帮助我。

   <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>

尝试编写一个命名函数,并在两个事件上调用它:

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

除了编写匿名函数作为回调之外,只是为了调用doSomething,您也可以将函数名称作为参数传递,通过不使用不必要的匿名函数混淆内存来获得一点性能:

$(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.
});

在加载过程中,您可以使用

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

然后点击

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

其中functionCallHere是在这些事件上调用的公共函数的名称。