jQuery动态内容计算

时间:2016-05-30 15:52:45

标签: javascript jquery

我的代码与静态部分完美配合,但是当我添加新行时,它不会计算字段。我做错了什么?

它还应计算通过“添加行”按钮添加的动态字段

Live DEMO

<div class="container">
<table id="t1" class="table table-hover">
        <tr>
            <th class="text-center">Start Time</th>
            <th class="text-center">End Time</th>
            <th class="text-center">Stunden</th>
          <th> <button type="button" class="addRow">Add Row</button></th>
        </tr>
        <tr id="row1" class="item">
            <td><input name="starts[]" class="starts form-control" ></td>
            <td><input name="ends[]" class="ends form-control" ></td>
            <td><input name="stunden[]" class="stunden form-control" readonly="readonly" ></td>
        </tr>
    </table>
</div>

JS

$(document).ready(function(){
$('.item').keyup(function(){

        var starts = $(this).find(".starts").val();
        var ends = $(this).find(".ends").val();
                    var stunden;
         s = starts.split(':');
         e = ends.split(':');

         min = e[1]-s[1];
         hour_carry = 0;
         if(min < 0){
             min += 60;
             hour_carry += 1;
         }
         hour = e[0]-s[0]-hour_carry;
         min = ((min/60)*100).toString()
         stunden = hour + "." + min.substring(0,2);

        $(this).find(".stunden").val(stunden);
});    

 // function for adding a new row
            var r = 1; 
            $('.addRow').click(function () {
            if(r<10){  
                r++;
                $('#t1').append('<tr id="row'+ r +'" class="item"><td><input name="starts[]" class="starts form-control" ></td><td><input name="ends[]" class="ends form-control" ></td><td><input name="stunden[]" class="stunden form-control" readonly="readonly" ></td></tr>');
                }
            });
                // remove row when X is clicked
            $(document).on("click", ".btn_remove", function () {
            r--;
            var button_id = $(this).attr("id");
                $("#row" + button_id + '').remove();
            });


  });

2 个答案:

答案 0 :(得分:2)

最好的方法是使用.on()事件,该事件用于将一个或多个事件处理程序附加到元素:

$(document).on('keyup', '.item',function(){
//your code
}

答案 1 :(得分:0)

当您向表中动态添加新行时,&#34; keyup&#34;事件不会自动绑定到它。基本上你需要包装&#34; keyup&#34;事件绑定到函数中,然后在您添加新行后调用它。有点像:

function rebindKeyup(){
      $('.item').keyup(function(){
      // Key up logic
      }
}