Html table with button on each row

后端 未结 2 1277
故里飘歌
故里飘歌 2020-12-16 21:21

I have a table with multiple rows and one column. Each table cell has a button in it. Like this:

相关标签:
2条回答
  • 2020-12-16 21:34

    Put a single listener on the table. When it gets a click from an input with a button that has a name of "edit" and value "edit", change its value to "modify". Get rid of the input's id (they aren't used for anything here), or make them all unique.

    <script type="text/javascript">
    
    function handleClick(evt) {
      var node = evt.target || evt.srcElement;
      if (node.name == 'edit') {
        node.value = "Modify";
      }
    }
    
    </script>
    
    <table id="table1" border="1" onclick="handleClick(event);">
        <thead>
          <tr>
              <th>Select
        </thead>
        <tbody>
           <tr> 
               <td>
                   <form name="f1" action="#" >
                    <input id="edit1" type="submit" name="edit" value="Edit">
                   </form>
           <tr> 
               <td>
                   <form name="f2" action="#" >
                    <input id="edit2" type="submit" name="edit" value="Edit">
                   </form>
           <tr> 
               <td>
                   <form name="f3" action="#" >
                    <input id="edit3" type="submit" name="edit" value="Edit">
                   </form>
    
       </tbody>
    </table>
    
    0 讨论(0)
  • 2020-12-16 21:38

    Pretty sure this solves what you're looking for:

    HTML:

    <table>
        <tr><td><button class="editbtn">edit</button></td></tr>
        <tr><td><button class="editbtn">edit</button></td></tr>
        <tr><td><button class="editbtn">edit</button></td></tr>
        <tr><td><button class="editbtn">edit</button></td></tr>
    </table>
    

    Javascript (using jQuery):

    $(document).ready(function(){
        $('.editbtn').click(function(){
            $(this).html($(this).html() == 'edit' ? 'modify' : 'edit');
        });
    });
    

    Edit:

    Apparently I should have looked at your sample code first ;)

    You need to change (at least) the ID attribute of each element. The ID is the unique identifier for each element on the page, meaning that if you have multiple items with the same ID, you'll get conflicts.

    By using classes, you can apply the same logic to multiple elements without any conflicts.

    JSFiddle sample

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