我想通过它的id删除任何行

时间:2015-08-15 20:25:12

标签: javascript

var numall = 2;
$('.add_row').click(function(){
    var displaytext = '';
    displaytext += ' <tr  id="tr'+numall+'"  ><td>';
    displaytext +='<input  type="text" name="length[]"    class="focuson selector remove_rows" onkeyup="func2()" size="20"/>';
    displaytext +='</td><td>';
    displaytext +='<input type="text" name="width[]" class="selector remove_rows" onkeyup="func2()" size="5"/>';
    displaytext +='</td><td>';
    displaytext +='<input  type="text" name="weight[]" class="selector remove_rows" onkeyup="func2()" size="15"/>';
    displaytext +='</td><td>';
    displaytext +='<input type="text" name="rate[]" class="selector remove_rows" onkeyup="func2()" size="15"/>';
    displaytext +='</td><td>';
    displaytext +='<input type="text" name="qty[]" id="dis[]" class="selector remove_rows"  onkeyup="func2()" size="15"/>';
    displaytext +='</td><td>';
    displaytext +='<input type="text" name="total[]" id="total[]" class="remove_rows" size="20"/> ';displaytext +='</td><td>';
    displaytext +='<input type="button"  id="' + numall + '" value="remove"/>';
    displaytext +='</td></tr>';

    $('#myTable tbody').append(displaytext);
    numall++;

    $('.focuson').focus();
    $(".selector").attr("required", true);

    $("#"+numall).click(function(){
        numall--;
        var buttonId = $(this).attr("id");
        //write the logic for removing from the array
        $("#tr"+ numall).remove();      
    });
});

1 个答案:

答案 0 :(得分:0)

根本不需要id和numall变量。给类删除按钮,然后找到父tr,然后删除它。

$('.add_row').click(function(){
    var displaytext = '';
    displaytext += ' <tr  ><td>';
    displaytext +='<input  type="text" name="length[]"    class="focuson selector remove_rows" onkeyup="func2()" size="20"/>';
    displaytext +='</td><td>';
    displaytext +='<input type="text" name="width[]" class="selector remove_rows" onkeyup="func2()" size="5"/>';
    displaytext +='</td><td>';
    displaytext +='<input  type="text" name="weight[]" class="selector remove_rows" onkeyup="func2()" size="15"/>';
    displaytext +='</td><td>';
    displaytext +='<input type="text" name="rate[]" class="selector remove_rows" onkeyup="func2()" size="15"/>';
    displaytext +='</td><td>';
    displaytext +='<input type="text" name="qty[]" id="dis[]" class="selector remove_rows"  onkeyup="func2()" size="15"/>';
    displaytext +='</td><td>';
    displaytext +='<input type="text" name="total[]" id="total[]" class="remove_rows" size="20"/> ';displaytext +='</td><td>';
    displaytext +='<input type="button"  value="remove" class="remove"/>';
    displaytext +='</td></tr>';

    $('#myTable tbody').append(displaytext);


    $('.focuson').focus();
    $(".selector").attr("required", true);

    $('.remove').on( "click", function() {

      $(this).parent().parent().remove();    
    });
});

演示:http://jsfiddle.net/afna6xnq/2/