2011-09-18 45 views
1

我试图抓住一个td值的每个检查行,并将其添加到自己找出总小时数。以下是我目前为止的内容。 (请注意,我试过的.text,.html和.VAL的变化。)试图获得一个动态的值

<tbody> 
    <tr class=""> 
     <td><input value="32" type="checkbox"></td> 
     <td>Keyword Optimization*</td> 
     <td class="hours" style="">5</td> 
     <td>hours</td> 
    </tr> 

</tbody> 

因此,在这种情况下,我期待能够加入“5”的总时数。这里是我的jQuery:

$("input:checked").each(function(){ 
hrs = parseInt($(this).find(".hours").val) + hrs; 
}); 
alert(hrs + " hours.") 

回答

0

找到搜索的子节点,这意味着“.hours”节点将不得不后裔的投入(这是错误的)。

另一件事是,class =“hours”是一个td元素,它没有.val(),但有.html()。

试试这个:

$("input:checked").each(function(){ 
    hrs = parseInt($(this).parent().parent().find(".hours").html()) + hrs; 
}); 
alert(hrs + " hours.") 

只是解释:

$(这)是输入

.parent()是TD

.parent()是tr

+0

你需要()后面的.html因为它是一种方法,而不是属性 – maxedison

+0

你已经注意到并且已经修复;) – galchen

+0

.html()返回一个字符串,所以+ hrs在最后将作为字符串连接而不是数值加法。另外,.parent()。parent()。find()比简单地执行$(this).siblings('。hours')效率低。 – maxedison

0

这会给你的检查行中的小时数:

$("input:checked").each(function(){ 
    var hrs = $(this).parent().siblings('.hours').text() * 1; //the *1 converts the string '5' to a number 
}); 
0

该文档说,发现看起来在节点的后代,所以我认为你需要:

hrs += parseInt($(this.parentNode.parentNode).find(".hours").val(), 10); 
0

尝试是这样的:

var updateHoursTotal = function() { 
    var hours = 0; 
    $('#yourtable') // within your table 
    .find('input:checked') // get the set of checked boxes 
    .closest('tr') // looking up to the enclosing tr 
    .find('.hours') // find the .hours cell within 
    .each(function(){ // for each 
     hours += parseInt($.trim($(this).text()), 10); // accumulate total hours 
    }); 
    $('span#counter').html(hours); // update displayed total somewhere in UI 
} 

你可以像这样的功能绑定到click事件每个复选框,例如。如果小时数可以是小数,则将一个变体解决方案留作练习。