Using jquery how to call a function and call another function from the previous when function execution is completed

StackOverflow https://stackoverflow.com/questions/19558035

문제

I have to perform a task based on jquery. When the page loads, the first jquery function will be called. Once the first function completes successfully, then it should automatically call the next function.

도움이 되었습니까?

해결책

Here is a working demo JSFIDDLE

JS:

function func_one()
{
    alert('func_one');           
    alert('Now call func_two');   
    func_two();
}

function func_two()
{
    alert('func_two');    
}
//jquery Function block that will be executed on page load
$(document).ready(function(){
    //call the function one
    func_one();
});

다른 팁

If the function is actually a function then just call it functionA() as per good ol' JavaScript. If it is an event then use Jquery trigger see http://api.jquery.com/trigger/

if it is possible then chaining the functions might also be a good idea.as in FunctionA().FunctionB();

you can 'pass' callback function to other functions. see example:

function one(callback) {
    // do stuff ...
    // do stuff ...
    // do stuff ...

    if (typeof(callback) === 'function') 
        callback();
}

function two() {
}

now, declare document ready and call function one. when it completes, we'll call function two.

$(document).ready(function(){
    one(function(){
        // code after 'one' ended
        two();
    });
});

that's the general idea. hope that helps.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top