Remove table row after clicking table row delete button

后端 未结 4 737
刺人心
刺人心 2020-12-01 08:00

Solution can use jQuery or be plain JavaScript.

I want to remove a table row after user has clicked the corresponding button contained in the table row cell so for e

相关标签:
4条回答
  • 2020-12-01 08:43

    you can do it like this:

    <script>
        function SomeDeleteRowFunction(o) {
         //no clue what to put here?
         var p=o.parentNode.parentNode;
             p.parentNode.removeChild(p);
        }
        </script>
    
        <table>
           <tr>
               <td><input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this)"></td>
           </tr>
           <tr>
               <td><input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this)"></td>
           </tr>
           <tr>
               <td><input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this)"></td>
           </tr>
        </table>
    
    0 讨论(0)
  • 2020-12-01 08:44

    Following solution is working fine.

    HTML:

    <table>
      <tr>
        <td>
          <input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this);">
        </td>
      </tr>
      <tr>
        <td>
          <input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this);">
        </td>
      </tr>
      <tr>
        <td>
          <input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this);">
        </td>
      </tr>
    </table>
    

    JQuery:

    function SomeDeleteRowFunction(btndel) {
        if (typeof(btndel) == "object") {
            $(btndel).closest("tr").remove();
        } else {
            return false;
        }
    }
    

    I have done bins on http://codebins.com/bin/4ldqpa9

    0 讨论(0)
  • 2020-12-01 08:46

    Using pure Javascript:

    Don't need to pass this to the SomeDeleteRowFunction():

    <td><input type="button" value="Delete Row" onclick="SomeDeleteRowFunction()"></td>
    

    The onclick function:

    function SomeDeleteRowFunction() {
          // event.target will be the input element.
          var td = event.target.parentNode; 
          var tr = td.parentNode; // the row to be removed
          tr.parentNode.removeChild(tr);
    }
    
    0 讨论(0)
  • 2020-12-01 08:52

    You can use jQuery click instead of using onclick attribute, Try the following:

    $('table').on('click', 'input[type="button"]', function(e){
       $(this).closest('tr').remove()
    })
    

    Demo

    0 讨论(0)
提交回复
热议问题