I'm using casperjs to fetch some data and I use variable inside funtion , but I can't use that variable outside that function
var website = 'test.com/index.php?id=';
casper.then(function () {
var var1 = this.getElementAttribute('input[type="text"][name="var1"]', 'value');
var var2 = this.getElementAttribute('input[type="text"][name="var2"]', 'value');
var var3 = this.getElementAttribute('textarea[name="var3"]', 'value');
var fullprint = (var1 + ', ' + var2 + ', ' + var3);
this.echo(fullprint);
});
var4 = (website + var2); // how to use var2 here in another then function
casper.thenOpen(function (var4) {
// some codes here
});
casper.run();
but I can't use that variable outside that function
You can't do so, because in JavaScript functions define a scope. Variables defined in this scope can be accessible by inner scopes (eg you define a couple of functions inside your function), but are inaccessible from outer scopes.
You could create a separate function (actually this is not needed for that you are looking for, but I think it's more readable the code this way) for getting the values you want, like below:
function getInputValue(varName){
return document.getElementAttribute('input[type="text"][name="'+varName+'"]', 'value');
}
Then you could change your code like below:
// At this object you could define properties
// that you would like to use in many places in your code.
var values = {};
casper.then(function () {
var var1 = getInputValue("var1");
var var2 = getInputValue("var2");
values.var2 = var2;
var var3 = getInputValue("var3");
var fullprint = (var1 + ', ' + var2 + ', ' + var3);
this.echo(fullprint);
});
casper.thenOpen(function (var4) {
var website = 'test.com/index.php?id=';
var4 = website + values.var2;
// some codes here
});
casper.run();
您需要在要从中访问每个内部函数的范围内声明var2
。
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.