[英]Javascript loop doesn't work in meteor
This should work but its not. 这应该有效,但事实并非如此。 What am I doing wrong?
我究竟做错了什么? I want to output "selected" to tags I have on a meteor page
我想将“selected”输出到我在流星页面上的标签
Template.editor.onRendered( function() {
var cats = ["Comedy","Action","Self Help"];
var arrayLength = cats.length;
for (var i = 0; i < arrayLength; i++) {
if(cats[i].indexOf(getDocument.category) != -1){
//found
var id = cats[i].trim().toLowerCase();
$("body").find("#"+id).attr("selected=selected");
console.log(id);
} else {
console.log(getDocument.category)
}
}
}
also 也
getDocument.category = ["Action", "Comedy"]
Maybe change 也许改变
$("body").find("#"+id).attr("selected=selected");
with 同
$("body").find("#"+id).attr("selected","selected");
Edit: 编辑:
if(cats[i].indexOf(getDocument.category) != -1){
I think you have here a wrong direction try this instead: 我认为你有一个错误的方向试试这个:
if(getDocument.category.indexOf(cats[i]) != -1){
You need to change a line to set selected attribute 您需要更改一行以设置所选属性
$("body").find("#"+id).attr("selected","selected");
Or try the following: 或者尝试以下方法:
$(document).find("#"+id).attr("selected","selected");
If I do not mistakenly understand what you asking for, you are trying to find the elements of 'cats' array if exist in the getDocument.category. 如果我没有错误地理解你要求的内容,那么你就是在getDocument.category中找到'cats'数组的元素。 If so, the above approach is wrong.
如果是这样,上述方法是错误的。 Take a look at this line:
看看这一行:
if(cats[i].indexOf(getDocument.category) != -1){...}
the result of this if checking
will always returning -1, the explanation is below: if checking
将始终返回-1,结果如下,解释如下:
cats[i]
will return the element (with index i) of cats, so if i=0 the result will be "Comedy". cats[i]
将返回cat的元素(带索引i),所以如果i = 0,结果将是“Comedy”。 Then, indexOf
will be executed on it, "Comedy".indexOf()
, to find the position of getDocument.category (which is an array). 然后,
indexOf
将在其上执行"Comedy".indexOf()
,以找到getDocument.category(这是一个数组)的位置。
That's means you are looking for an array inside a string? 那意味着你在字符串中寻找一个数组? that's will not work.
那是行不通的。
Actually, we can check if an element exists in array with includes methods. 实际上,我们可以检查包含方法的数组中是否存在元素。 So maybe the complete code will be looked like this:
所以也许完整的代码看起来像这样:
Template.editor.onRendered(function() {
var cats = ["Comedy", "Action", "Self Help"];
var arrayLength = cats.length;
for (var i = 0; i < arrayLength; i++) {
if (getDocument.category.includes(cats[0])) {
//found
var id = cats[i].trim().toLowerCase();
$("body").find("#" + id).attr("selected=selected");
console.log(id);
} else {
console.log(getDocument.category)
}
}
})
Hope this will help, thanks 希望这会有所帮助,谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.