[英]jquery function call on page both onload and onclick?
我正在使用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
是在这些事件上调用的通用函数的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.