简体   繁体   中英

Passing parameters to function in CasperJS's evaluate

How can I pass a parameter to a function within CasperJS's evaluate?

    //Should be logged in at this point
    casper.then(function() {
        var counter = 0;
        var cap = 500;

        this.evaluate(function(counter) {
            var children = $('.companies-using-service').children();

            while (counter < children.length) {
                child = children[counter];
                console.log($(child).find('a').attr('data-hint'));
                counter++;
            }
        }, counter);
    });
};

var scrapeClients = function(counter) {
    var children = $('.companies-using-service').children();

    while (counter < children.length) {
        child = children[counter];
        console.log($(child).find('a').attr('data-hint'));
        counter++;
    }
}

Above, I am able to pass parameters in using an unamed function. However, I wish to pass in the function scrapeClients to the evaluate function. In that case, I tried the following this.evaluate(scrapeClients(counter), counter) . However, this does not work and the error says that it could not find $ variable.

Functions are first-class citizen in JavaScript. You can treat them in the same way as variables. You can pass them around. This means that you don't want

this.evaluate(scrapeClients(counter), counter)

but rather

this.evaluate(scrapeClients, counter)

In the first case, you're actually calling the function directly. Since the function uses some page properties that are only available inside of casper.evaluate , this will throw an error and stop the script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM