2012-12-03 49 views
0

我有一套jQuery和一般的JavaScript函数在js中。现在我想避免某些功能在某些情况下可用。例如:jQuery的避免条件运行功能

function test() { 
    alert("hi"); 
} 

function avoid() { 
    if(condition) { 
    //here avoid to call test 
    } 
} 

感谢

+1

你能否分享一些信息来检查你的需求?一个jsfiddle链接会很好。 – Rups

+0

Ehrrm ..我建议只是*不打电话*的功能。 – jAndy

+0

可以在'test()'本身中评估'condition'吗?例如'function test(){if(!condition){alert(“hi”); }}'? –

回答

1

如果你想删除没有错误的功能(提供的函数的调用者不希望返回的结果),你可能会做

function avoid() { 
    if(condition) { 
    test = function(){}; // does nothing 
    } 
} 

请注意,如果您的avoid函数处于不同的范围,则可能需要进行调整。例如,如果test是在全球范围内定义的,那么你会做window.test = function(){};

+3

您可以添加'test.old = test'来保留旧功能 – PitaJ

0

我不知道如果我理解你的问题很好,但如果调用你的测试功能是避免函数中象下面这样:

function test() { 
    alert("hi"); 
} 

function avoid() { 
    if(condition) { 
    //here avoid to call test 
    return false; 
    } 
    test(); 
} 

然后一个简单的返回错误可以解决你的问题,我不知道,如果你的函数使用的事件,但如果是这样的话,这是一个很好的职位,你可以阅读有关的preventDefault并返回false:enter link description here

如果测试的回避水平如下:

function test() { 
alert("hi"); 
} 

function avoid() { 
    if(condition) { 
    //here avoid to call test 
    return false; 
    } 
    return true; 
} 

// below is your functions call 
    check = avoid(); 

    if(check){ 
    test(); 
    } 

这篇文章介绍了如何从一个函数退出:enter link description here

我希望帮助。