我有这个奇怪的问题,无法理解该函数的范围如何在文件中起作用。
function f3() {
}
function f2() {
f3(); // Cannot find variable: f3
}
function f1() {
f3(); // works fine
f2(); // works fine
}
f1();
实际代码。
var page = require('webpage').create();
function fPrintObj(obj) {
// Object properties
var output = '';
for (var property in obj) {
output += property + ': ' + obj[property]+'; ';
}
console.log(output);
}
function fGetXpathAd() {
xPathAd = "//div[@class='col-xs-12 col-sm-12 col-md-12 col-lg-12 home-solutions-head']";
console.log(xPathAd);
var adcopy = document.evaluate( xPathAd, document, null, XPathResult.STRING_TYPE, null);
fPrintObj(adcopy); //DOES NOT WORK
return adcopy;
}
function main(status) {
console.log('Evaluating ad-copy.... ');
var a = page.evaluate(fGetXpathAd);
// fPrintObj(a); // WORKS
phantom.exit();
}
// fSetRandomUserAgent();
page.open('https://www.position2.com', main );
错误
ReferenceError: Can't find variable: fPrintObj
phantomjs://webpage.evaluate():6 in fGetXpathAd
phantomjs://webpage.evaluate():8
phantomjs://webpage.evaluate():8
答案 0 :(得分:1)
在phantomjs中,page.evaluate是一个页面上下文,你不能调用在它之外定义的函数。你应该将你的函数作为第二个参数传递给page.evaluate,如下所示:
function fGetXpathAd(fPrintObj) {
xPathAd = "//div[@class='col-xs-12 col-sm-12 col-md-12 col-lg-12 home-solutions-head']";
console.log(xPathAd);
var adcopy = document.evaluate( xPathAd, document, null, XPathResult.STRING_TYPE, null);
fPrintObj(adcopy); //WILL WORK
return adcopy;
}
function main(status) {
console.log('Evaluating ad-copy.... ');
var a = page.evaluate(fGetXpathAd, fPrintObj);
// fPrintObj(a); // WORKS
phantom.exit();
}
我希望这会有所帮助。