javascript onload 和 onclick 页面上的 jquery 函数调用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10892106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery function call on page both onload and onclick?
提问by Kashif Waheed
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.
我正在处理 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>
采纳答案by ahren
$(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.
});
回答by hielsnoppe
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:
除了编写匿名函数作为回调,只是为了调用doSomething
,您还可以将函数名称作为参数传递,通过不使用不必要的匿名函数来混淆内存来获得一点性能:
$(document).ready(doSomething);
$(yourElem).on("click", doSomething);
回答by Joseph
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.
functionCallHere
对这些事件调用的公共函数的名称在哪里。