我真的不知道如何解释我的问题,所以我贴上了下面的代码。基本上,我有三个以数字结尾的变量,我想在一个循环中调用每个变量,它引用循环索引。
textLine1 = "This is line 1";
textLine2 = "This is line 2";
textLine3 = "This is line 3";
function text(i) {
for (i = 1; i < 4; i++) {
$('.line__' + i).html(textLine(i) would go here);
}
}
text();发布于 2016-01-30 01:22:22
将变量放入数组中,然后访问适当的数组元素:
var textLine = ["This is line 1", "This is line 2", "This is line 3"];
function text() {
for (var i = 0; i < textLine.length; i++) {
$('.line__' + (i+1)).html(textLine[i]);
}
}
text();备注:
0索引的,所以第一个数组元素位于textLine[0],所以您需要更改for循环以从0开始。i应该在var中声明为局部变量,因此它不是偶然的全局变量(我不知道为什么要将它声明为参数,因为它不是以这种方式使用的)。for循环应该与textLine.length相比,而不是硬编码常量。一种更紧凑的编码方式是这样的:
var textLine = ["This is line 1", "This is line 2", "This is line 3"];
textLine.forEach(function(item, index) {
$('.line__' + (index+1)).html(item);
});发布于 2016-01-30 01:26:28
正如其他人所建议的那样,数组最适合用于此目的。
但是对于那些无法控制如何声明变量的人,您可以使用以下方法。
textLine1 = "This is line 1";
textLine2 = "This is line 2";
textLine3 = "This is line 3";
function text(i) {
for (i = 1; i < 4; i++) {
$('.line__' + i).html(window['textLine' + i]);
}
}
text();<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="line__1"></div>
<div class="line__2"></div>
<div class="line__3"></div>
发布于 2016-01-30 01:58:39
var textLines = ["This is Line 1", "This is Line 2","This is Line 3"];
function text() {
for (var i = 0; i < textLines.length; i++) {
$('.line__' + (i + 1)).html(textLines[i]);
}
}
text();<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="line__1"></div>
<div class="line__2"></div>
<div class="line__3"></div>
https://stackoverflow.com/questions/35096883
复制相似问题