简体   繁体   English

删除表行除第一行外

[英]Delete Table Row Except in First Row

I have a form which allows the user to add a new table row via a button in the bottom row which all is working well. 我有一个表单,允许用户通过底行的按钮添加一个新的表行,这一切都运行良好。 I now need to also add the functionality to have an additional button to allow them to delete a table row. 我现在还需要添加功能以获得一个额外的按钮,以允许他们删除表格行。

I gather the simplest method would be to use: 我收集最简单的方法是使用:

$(this).closest('tr').remove();

but I'm having trouble integrating this into the existing functionality. 但我无法将其集成到现有功能中。 I also only need the "delete" button to appear on all rows except the first row (ie users can delete all rows except the first one). 我还只需要“删除”按钮出现在除第一行之外的所有行上(即用户可以删除除第一行之外的所有行)。 I've setup a jsfiddle here that demonstrates my current functionality: 我在这里设置了一个jsfiddle来演示我当前的功能:

http://jsfiddle.net/fmdataweb/daayf/1/ http://jsfiddle.net/fmdataweb/daayf/1/

So in my example when the user clicks the "Add another activity" button it should create the new table row as it currently does but also add the "delete" button which deletes that row. 因此,在我的示例中,当用户单击“添加另一个活动”按钮时,它应该像当前一样创建新的表行,但也添加删除该行的“删除”按钮。 I've currently hard-coded the "delete" button to the first row as I'm now sure how to make it appear only for new rows created via the "add new activity" button. 我目前已经将“删除”按钮硬编码到第一行,因为我现在确定如何使其仅显示通过“添加新活动”按钮创建的新行。

Few changes 几乎没有变化

In the starting markup, add the classes addbtn and delbtn also hide the delete button 在起始标记中,添加类addbtndelbtn也隐藏删除按钮

<td>
    <input type="button" class="button mt5 addbtn" value="Add another activity" id="button1" name="button2" />
</td>
<td>
    <input type="button" class="button mt5 delbtn" value="Delete" id="deleteRowButton" name="deleteRowButton" style="display: none"/>
</td>

Then 然后

$('#lastYear').on('click', '.delbtn', function () {
    $(this).closest('tr').remove()
});

var newIDSuffix = 2;
$('#lastYear').on('click', '.addbtn', function () {
    var thisRow = $(this).closest('tr')[0];
    $(thisRow).find('.delbtn').show();

    var cloned = $(thisRow).clone();
    cloned.find('input, select').each(function () {
        var id = $(this).attr('id');
        id = id.substring(0, id.length - 1) + newIDSuffix;
        $(this).attr('id', id);
    });

    cloned.insertAfter(thisRow).find('input:text').val('');
    cloned.find('.delbtn').hide();
    cloned.find("[id^=lastYearSelect]")
    .autocomplete({
        source: availableTags,
        select: function (e, ui) {

            $(e.target).val(ui.item.value);
            setDropDown.call($(e.target));
        }
    }).change(setDropDown);

    $(this).remove();
    newIDSuffix++;
});

Demo: Fiddle 演示: 小提琴

看看这一个!

if($("table tr").length > 1) {
$(this).parent().parent("tr").remove(); }

Try this 尝试这个

On your Delete Button 在删除按钮上

$('#lastYear').on('click', '#deleteRowButton', function(e){
   $(this).closest('tr').remove()
})

First of all I renamed your Button1 for your Adding a Row to addRowButton and then I change the delegate method to be more specific to addRowButton that is from 首先,我将您的Button1重命名为addRowButton Row to addRowButton ,然后我将委托方法更改为更具体的addRowButton来自

$('#lastYear').delegate('input[type="button"]'

To like this: 喜欢这个:

$('#lastYear')delegate('input[type="button"][id^="addRow"]'

Then inside the delegate method specifically after 然后专门在委托方法之后

 $(this).attr('id', id);

I add after that the one below: 之后添加以下内容:

 var checkid = $(this).attr('id').substring(0,id.length-1);

 if (checkid == 'deleteRowButto') // the 'deleteRowButto' is not a mistake
     {
         $(this).click(function() {
             $(this).closest("tr").remove(); // I assign an onclick for the delete button in order to remove a specific row
          });
      }

Edit: 编辑:

I made some improvements that once the row is deleted the previous add button is shown so I add the code below: 我做了一些改进,删除行后会显示上一个添加按钮,所以我添加下面的代码:

 var showmenow =  $(this).closest("tr").prev().find("td:eq(5)").find("input[type='button']");               
 $(showmenow).show();
             $(this).closest("tr").remove(); 
             });

And instead of removing the button in your original code: 而不是删除原始代码中的按钮:

$(this).remove();
newIDSuffix++;

I use hide instead: 我改用hide来代替:

$(this).hide();
newIDSuffix++;

See the new jsfiddle that I created. 看看我创建的新jsfiddle

Since you want to use the first row as template for all other row but do not want to have a delete on the all the other rows we should insert the delete only during first insertion in java script.Check this demo out i modified your fiddle for this to work. 由于您希望将第一行用作所有其他行的模板但不希望在所有其他行上删除,我们应该仅在首次插入java脚本时插入删除。检查此演示我修改了您的小提琴这个工作。

if(cloned.find('input.mt5[value="Delete"]').length==0){
   cloned.find('.mt5').each(function(){
       cloned.append($('<td><input type="button" class="button mt5" value="Delete" id="deleteRow'+newIDSuffix+'" name="deleteRowButton" /></td>'));
   })
}

now for handling the delete events 现在用于处理删除事件

$('#lastYear').delegate('input.button[value="Delete"]', 'click', function () {
    var thisrow=$(this).parent().parent();
    var button=thisrow.find("input.button[value='Add another activity']");
    if(button.length>0){
        var buttoncell=button.parent().detach();
        var prevrow=thisrow.prev();
        var prevDelete=prevrow.find('input.button[value="Delete"]');
        var previd=(prevDelete.length>0)?prevDelete[0].id:'deleteRow1';
        buttoncell.children()[0].id=previd.replace('deleteRow','button');
        prevrow.find('input:text:last').parent().after(buttoncell);
    }
    thisrow.remove();
 });

Demo: http://jsfiddle.net/vwdXD/2/ 演示: http//jsfiddle.net/vwdXD/2/

You have got it right for the most part except for the small oversight here and there. 除了这里和那里的小疏忽之外,你在大多数时候都做对了。 I have fixed your code for you and you can find it here: http://jsfiddle.net/ManojRK/86Nec/ . 我已经修复了你的代码,你可以在这里找到它: http//jsfiddle.net/ManojRK/86Nec/

Please try to understand the changes by comparing your version and my version using a Code Diff Tool (like http://www.quickdiff.com ). 请尝试使用代码差异工具(如http://www.quickdiff.com )比较您的版本和我的版本来了解更改。 It will teach you a lot. 它会教你很多。

Changes Made: 做出的改变:

  1. I have used styles to show and hide your buttons. 我使用样式来显示和隐藏按钮。 This is not the only way to do it. 这不是唯一的方法。 But since you are cloning rows to add, using styles will make your JavaScript simple. 但是由于您要克隆要添加的行,因此使用样式将使您的JavaScript变得简单。 This is a lot less buggy and less susceptible to changes. 这样可以减少很多错误并且不易受到变化的影响。
  2. I have introduced css classes to differentiate Add Another Activity and Delete buttons for the click event. 我已经介绍了css类来区分click事件的Add Another ActivityDelete按钮。

Hope it helps you understand. 希望它能帮助你理解。

I used the jsfiddle that you provided in hopes of being more direct in terms of answering your question. 我使用了你提供的jsfiddle,希望在回答你的问题方面更直接。 The method I took was to: 我采取的方法是:

  1. Check if the add or delete button was pressed 检查是否按下了添加或删除按钮
  2. If the delete button was pressed, check if its the delete button contained within the first row (actually the third row, but it's the first row with user input). 如果按下了删除按钮,请检查第一行中是否包含删除按钮(实际上是第三行,但它是用户输入的第一行)。 If the delete button is in the first row, do nothing 如果删除按钮位于第一行,则不执行任何操作
  3. If the delete button was not in the first row, create an 'add activity' button in the previous row and remove the clicked button's parent row. 如果删除按钮不在第一行中,请在上一行中创建“添加活动”按钮,然后删除单击按钮的父行。

Step 1: 第1步:

    // let's check whether they clicked the add or delete button
    if ( $(this).val() == 'Add another activity' ) { // if the add button was clicked

Step 2-3: 第2-3步:

       if ( $(thisRow).index() == 2 ) { // if it's the first row, don't let them delete
            return false;
        } else { // if it is not the first row remove this row and create an 'add' button in first row
            $(thisRow).prev().find('td:last').prev().append('<input type="button" class="button mt5" value="Add another activity" id="button2" name="button2">');
            $(thisRow).remove();
        }

Here's a fiddle for ya: http://jsfiddle.net/daayf/22/ 这是你的小提琴: http//jsfiddle.net/daayf/22/

I placed a couple comments in the code to help out a bit. 我在代码中添加了一些注释以帮助解决一些问题。 My edits were at: 我的编辑是:

  • Line 275-276 第275-276行
  • Line 300-307 300-307号线

Hope this helps out! 希望这会有所帮助!

我建议为每一行动态添加一个id属性,这样你就可以用jQuery引用那个id

You can set a specific class for the buttons like this 您可以为这样的按钮设置特定的类

<input type="button" class="button mt5 deleteButton" value="Delete" id="deleteRowButton" name="deleteRowButton" />

and add this code to jquery 并将此代码添加到jquery

$('.deleteButton').on('click',function(){
    $(this).parent().parent().remove();
});

this jquery deletes the grandparent of the input with deleteButton Class(the delete button), which is the row it is located in. 这个jquery用deleteButton Class(删除按钮)删除输入的祖父,它是它所在的行。

怎么样这个?

$(this).find('tr').length > 0 ? $(this).closest('tr').remove() : ;

Why is your "add new activity" and "delete" having the same class "button mt5"? 为什么你的“添加新活动”和“删除”具有相同的类“按钮mt5”? not sure if space is allowed for the name of a class. 不确定类的名称是否允许空格。

You may want to refer to my table here http://jsfiddle.net/yvonnezoe/nbrSR/1/ :DI have a fixed row on top and dynamic rows following that can be deleted. 你可能想在这里参考我的表http://jsfiddle.net/yvonnezoe/nbrSR/1/:DI在顶部有一个固定的行,可以删除后面的动态行。

My new row is created as below: 我的新行创建如下:

var str = '<tr id="' + rowID + '">' + '<td>' + index + '</td><td>' + rowID + '</td><td class="type_row_' + textInput + '">' + type + '</td><td class="feedback number">' + textInput + '</td>' + '<td id="status_'+rowID+'"></td>' + '<td><input type="checkbox" name="CB" id="monitor_' + rowID + '" class="custom" data-mini="true" /><label for="CB"> </label></td><td class="outputRemove">x</td>' + '</tr>';
$('#status_table tr:last').after(str);

The remove buttons are having a same class. 删除按钮具有相同的类。 So the rows can deleted when clicked. 因此,单击时可以删除行。

$('#status_table').on('click', '.outputRemove', function () {
$(this).closest('tr').remove();
$('#status_table tbody tr').find('td:first').text(function (index) {
    return ++index;
});

}); });

Hope it inspires you somehow :) 希望它以某种方式激励你:)

very simple way 很简单的方法

function remove_point_item(th) {
        var tr = $(th).closest("tr");
        var _counter=0;
        $(tr.siblings('tr')).each(function(){
            _counter++;
        });
       if(_counter!=1){           
        tr.remove();
       }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM