我有一些php,javascript和html代码。我有几行在2个函数中是相同的。当页面加载时我只想要其中一个函数基本上执行而不是另一个,我怎么能阻止另一个执行?示例如下:
Function 1()
document.getElementById('field1').length=$field1_numrows
Function 2()
document.getElementById('field1').length=$field1_numrows
我不希望第二个函数运行,现在在第一个函数中出现了一些代码,因此函数2实际上覆盖了函数1的值。
答案 0 :(得分:1)
你需要的只是某种旗帜。例如:
var wasExecuted;
function runOnce(){
if( wasExecuted ){
return;
}else{
wasExecuted = true;
document.getElementById('field1').length=$field1_numrows;
}
}
runOnce(); //this will run through the 'else'
runOnce(); //this will exit the runOnce function (as the flag has been set to true)
答案 1 :(得分:0)
你有没有理由不在括号中捕捉你的功能?请尝试以下代码。
window.onload = function(){
document.getElementById('field1').length=$field1_numrows
};
function 2(){
document.getElementById('field1').length=$field1_numrows
}
答案 2 :(得分:0)
旗帜值怎么样? 像:
var myFlag = false;
function 1(){
if(!myFlag){
document.getElementById('field1').length=$field1_numrows;
myFlag = true;
}
}
function 2(){
if(!myFlag){
document.getElementById('field1').length=$field1_numrows;
myFlag = true;
}
}
答案 3 :(得分:0)
这里可能是一个更通用的解决方案:
var already_executed = (function () {
var done = {};
return function (tag) {
var res = done[tag];
done[tag] = true;
return res;
}
})();
标签用于标识一组功能。只会执行该组中的第一个。
您可以通过为不同的标记分配不同的功能来重用相同的机制。
例如:
function a() {
if (already_executed("a_or_b")) return;
console.log ("a is executing");
// rest of the code
}
function b() {
if (already_executed("a_or_b")) return;
console.log ("b is executing");
// rest of the code
}
function c() {
if (already_executed("c_or_d")) return;
console.log ("c is executing");
// rest of the code
}
function d() {
if (already_executed("c_or_d")) return;
console.log ("d is executing");
// rest of the code
}
调用
a();
b();
c();
d();
将导致
a is executing
c is executing
所有这一切,我认为重构你的代码将比依赖这样的黑客更好的投资。在我看来,在这种机制背后隐藏错误的代码是一种麻烦。