调用.each函数

时间:2013-10-10 09:18:34

标签: javascript jquery

我有一个包含数据行的表:

<tbody>                       
   <tr class="rows">
     <td><input type="text" name="total" value="3500.00" id="total" class="price"></td>
     <td>$<input type="text" value="23.00" name="customerS" id="customerS" class=""></td>
   </tr>

  <tr class="rows">
     <td><input type="text" name="total" value="3900.00" id="total" class="price"></td>
     <td>$<input type="text" value="3446.00" name="customerS" id="customerS" class=""></td>
  </tr>                            
</tbody>

我想使用行的ID来调用函数。

format('total', 'customerS');

我无法弄清楚如何使用.each调用函数格式,以便为每个tr(行)调用格式。请让我知道,谢谢。

4 个答案:

答案 0 :(得分:3)

链接each()

$('tr.rows').each(function(){
    format('total', 'customers');
});

虽然参数应该是变量,取决于tr元素的某些属性,但您需要提供更多详细信息。

但值得注意的是,您在id s中包含的元素中复制了tr,这是无效的HTML。

答案 1 :(得分:1)

试试这个

$(".rows").each(function(element){
var curretnRow = $(element);    
// apply your function here
});

$(".rows") =&gt;这将获得所有类型为“行”的TR。

.each(function(element){} =&gt;这将迭代集合中的每个元素,为您提供对'element'变量中当前元素的引用。

注意:我可以看到每个TR都有持有相同ID的元素,这在处理重复元素时不是正确的方法。 我认为处理类名并尝试为每个元素设置唯一ID应该是您拥有可维护代码的第一步。

我希望现在对您更清楚,请告诉我这是否解决了您的问题。

答案 2 :(得分:1)

您不应对多个元素使用相同的ID。你可以改用class。

      <tbody>                       
             <tr class="rows">
                 <td><input type="text" name="total" value="3500.00" id="total"   class="price">
                 </td>
                 <td>$<input type="text" value="23.00" name="customerS" class="customerS" class=""></td>
             </tr>

             <tr class="rows">
                 <td><input type="text" name="total" value="3900.00" id="total"   class="price">
                 </td>
                 <td>$<input type="text" value="3446.00" name="customerS" class="customerS" class=""></td>
             </tr>                            
                </tbody>

然后

jQuery(".customerS").each(function(index, element) {
    blah blah...
});

答案 3 :(得分:1)

你可以这样做:

$(this).closest('tr').each(function() {...code...});