通过<input />标记更新数组的值

时间:2014-03-16 21:49:10

标签: javascript jquery arrays html5 event-listener

我有以下三个标签:

<input class="forLoopIndex" id="typicalElement" type="text" name="k" size="1" placeholder="10">

<input class="forLoopIndex" type="text" name="n" size="1" placeholder="n">

<input class="forLoopIndex" type="text" name="i" size="1" placeholder="i">

现在我有一个事件监听器,它检查值何时进入,然后将其存储在数组中。我希望数组只保持3个值。因为我需要使用第三和第二个东西,但我需要看看它们何时改变。以下是JS:

  forloops.keyup(function () {
    if (forLoopIndex.length < 2 && forLoopIndex >= 0) {
        forloops.each(function () {
            forLoopIndex.push($(this).val());
            appendingToSigmaLimit();
            console.log(sigmaLimit.val());
            console.log(forLoopIndex);
        });
    } else if (forLoopIndex.length > 2) {
        forLoopIndex = [];
    }
});

现在,问题在于,只有在我再次更改三个输入的值之后,这些值才会更新。我有一种感觉,逻辑的方式在我的JS中就是让它做到这一点。我只需要在每次更改输入值时更新值。有什么想法吗?

谢谢,

中号

1 个答案:

答案 0 :(得分:1)

不确定您的期望,这样的内容将分别更新每个输入

var forloops= $('.forLoopIndex');
var forLoopIndex = [];
forloops.keyup(function () {
    forloops.each(function (i, e) {
           forLoopIndex[i] = $(this).val();
           console.log(i);
           console.log(forLoopIndex);
    });
});

FIDDLE

无循环编辑:

var forloops= $('.forLoopIndex');
var forLoopIndex = [];
forloops.keyup(function () {
    forLoopIndex[$(this).index('.forLoopIndex')] = $(this).val();
    console.log(forLoopIndex);
});

FIDDLE