[英]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.