如何解决声明 Cheerio 变量的问题
我想将变量 $
声明给对象内的 cheerio.load
函数,以便我可以从我的任何函数访问cheerio 函数。
但是,无论何时我都会收到错误 this.$ is not a function
我正在使用的代码
var spl = {
main: function() {
fs.readFile("index.html","utf8",function(err,data){
if(err) throw err;
this.$ = cheerio.load(data) // Using context.$ resulted in the same problem
});
this.hasTitleTag() // this gives the error this.$ is not a function
},hasTitleTag: function() {
return this.$('title').length > 0 ? true : false;
}
};
我猜不是在我的对象中创建一个变量 $
它只是为 main
函数创建它,我已经在线阅读以使用 context
关键字,但这并没有似乎也没有做任何事情,我也找不到其他解决方案
解决方法
readFile
是异步的,因此函数调用发生在文件加载之前。这样做:
var spl = {
main: function() {
let data = fs.readFileSync("index.html","utf8");
this.$ = cheerio.load(data)
this.hasTitleTag() // this gives the error this.$ is not a function
},hasTitleTag: function() {
return this.$('title').length > 0 ? true : false;
}
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。