2009-03-06 46 views
2

我有一个表在单独的列中包含许多对文本输入字段。我想遍历第一列中的输入字段,并使用这些值来设置相邻列中相应输入字段的值。同时在jQuery中对两组元素进行迭代

<table> 
    <tr> 
     <td><input type="text" class="left" /></td> 
     <td><input type="text" class="right" /></td> 
    </tr> 
    <tr> 
     <td><input type="text" class="left" /></td> 
     <td><input type="text" class="right" /></td> 
    </tr> 
    ... 
</table> 

我刚开始学习jQuery,所以答案很明显。到目前为止,我只有

$("input.left").each(function() { 
    // use the value of $(this) to set the 
    // value of the text field to the .right 
}) 

回答

2

很多方法可以做到这一点。这是一个。

$("tr").each(function() { 
    $(this).find(":last-child input").val($(this).find(":first-child input").val()); 
}); 

或其他:

$("input.left").each(function() { 
    $(this).parent().nextSibling().find("input.right").val(this.value); 
}); 

等。

6

你想要做的是被称为'zip'操作。这在功能性编程语言中看起来很多。它是一个将两个长度相等的序列组合成一个包含一对元素(或n元组)的单一序列的函数。

在这里你可以找到jQuery的'zip'的实现。这是一个jQuery插件。 Available on Google Code

看起来你可以使用它像tihs:

$.zip($("input.left"), $("input.right")).each(function() { 
    var left = this[0]; 
    var right = this[1]; 
}) 
+0

不知道这存在! – alex 2009-03-06 05:35:35