我有一个功能(200+行代码)。它可以在页面加载时或在某些点击事件期间运行。现在如何决定是否在页面加载中运行函数?
这是一个简单的测试代码。也保存在http://jsfiddle.net/EjcTk/,谢谢。
<script>
jQuery(document).ready(function(){
function ABC() {
//many code here
if(someelse===undefined){
//if by click, do some code.
//if by page loading, do not run these code.
alert('ok');//check if it works.
}
}
$(document).ready(function() {
var someelse = 1;
ABC();
});
$('#click').click(function() {
ABC();
});
});
</script>
<div id="click">test</div>
答案 0 :(得分:1)
试试这个http://jsfiddle.net/EjcTk/2/
var someelse = 0;
$(document).ready(function() {
someelse = 0;
ABC();
});
$('#click').click(function() {
someelse = 1;
ABC();
});
function ABC() {
if (someelse == 0) {
alert('onload');
} else alert('onclick');
}
答案 1 :(得分:1)
试试这个:
function ABC(status) {
//many codes here
if(status==='click'){
//if by click, do some code.
//if by page loading, do not run these code.
alert('ok');//check if it works.
}
}
$(document).ready(function() {
ABC('default');
});
$('#click').click(function() {
ABC('click');
});
答案 2 :(得分:1)
Pass boolean argument
在函数中知道它是在加载时调用还是从其他地方调用
jQuery(document).ready(function(){
function ABC(isOnLoad) {
//many code here
if(isOnLoad){
//if by click, do some code.
//if by page loading, do not run these code.
alert('ok');//check if it works.
}
}
$(document).ready(function() {
ABC(true);
});
$('#click').click(function() {
ABC(false);
});
});
答案 3 :(得分:0)
好吧,根据您设置点击处理程序的方式,您可以执行以下操作:
if(this===window)
//it's running in page load
else
//it's being run as a click handler
在某些情况下,这不起作用,例如,如果您手动修改this
,或者您的点击处理程序设置如下:
<a href="#" onclick = "ABC()">Click</a>
在这种情况下,this
仍会引用窗口。如果是这种情况,你可以这样做:
jQuery(document).ready(function(){
this.someVar = true;
function ABC(){
if (window.someVar === true)
//its running in doc.ready
else
//its running elsewhere
}
this.someVar = false;
//...
//rest of code
//...
});