我是新手,所以我想我错过了一些简单的东西。 foor循环工作正常,但在其中我得到一个未定义的变量
var categories_info = ["historia","excelencia","arte","social","instalaciones","padres","familia"];
for ( var i = 0; i < categories_info.length; i++) {
$("#showMe-"+categories_info[i]).click(function(){
$(".info."+categories_info.[i]).addClass("info-show");
console.log(".info."+categories_info[i]); //debug is undefinded
});
};
答案 0 :(得分:3)
你需要创建一个像
这样的闭包var categories_info = ["historia", "excelencia", "arte", "social", "instalaciones", "padres", "familia"];
for (var i = 0; i < categories_info.length; i++) {
(function(i) {
$("#showMe-" + categories_info[i]).click(function() {
$(".info." + categories_info[i]).addClass("info-show");
console.log(".info." + categories_info[i]);
});
})(i);
};
此方法称为IIFE
基本上,当发生实际点击时,发生的变量i
对回调不可用。
但是,通过在自动执行的匿名函数中传递i
,您创建了一个闭包,它将保留i
并可供点击处理程序访问。
答案 1 :(得分:1)
使用闭包。变化:
> SECDraft = read.csv("SECDraftScouting.csv", stringsAsFactors=FALSE)
> SECcorpus = Corpus(VectorSource(SECDraft$Report))
> SECcorpus = tm_map(SECcorpus, tolower)
> SECcorpus = tm_map(SECcorpus, PlainTextDocument)
> SECcorpus = tm_map(SECcorpus, removePunctuation)
> SECcorpus = tm_map(SECcorpus, removeWords, c("strengths", "weaknesses", "notes", stopwords("english")))
> SECfrequencies = DocumentTermMatrix(SECcorpus)
> SECallReports = as.data.frame(as.matrix(SECfrequencies))
> wordcloud(colnames(SECallReports), colSums(SECallReports), random.order = FALSE, max.words = 200, scale=c(2, 0.25))
要:
$("#showMe-"+categories_info[i]).click(function(){
$(".info."+categories_info.[i]).addClass("info-show");
console.log(".info."+categories_info[i]); //debug is undefinded
});