是否可以在引用索引的循环中调用jQuery中的变量

时间:2016-01-30 01:19:03

标签: javascript jquery variables

我真的不确定如何解释我的问题所以我在下面粘贴了我的代码。我基本上有三个以数字结尾的变量,我想在一个引用循环索引的循环中调用每个变量。

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();

4 个答案:

答案 0 :(得分:2)

有没有理由你不能将这些声明为数组?

var textLines = ["This is Line 1", "This is..."];

function text() {
  for (var i = 0; i < textLines.length; i++) {
    $('.line__' + i + 1).html(textLine[i]);
  }
}

答案 1 :(得分:2)

将变量放入数组中,然后访问相应的数组元素:

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();

注意:

  1. 数组被0编入索引,因此第一个数组元素位于textLine[0],因此您需要将for循环更改为从0开始。
  2. 您的本地变量i应该声明为var的局部变量,因此它不是偶然的全局变量(我不知道为什么你将它声明为参数,因为它不是用这种方式)。
  3. 为了便于维护,您的for循环应与textLine.length进行比较,而不是硬编码常量。
  4. 更简洁的编码方式就是这样:

    var textLine = ["This is line 1", "This is line 2", "This is line 3"];
    
    textLine.forEach(function(item, index) {
        $('.line__' + (index+1)).html(item);
    });
    

答案 2 :(得分:0)

正如其他人所说,阵列最适合此目的。

但对于无法控制变量声明方式的人,可以使用以下内容。

&#13;
&#13;
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();
&#13;
<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>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

&#13;
&#13;
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();
&#13;
<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>
&#13;
&#13;
&#13;