jQuery replaceWith Inside Loop malfunction

jQuery replaceWith Inside Loop malfunction

本文关键字:malfunction Loop Inside replaceWith jQuery      更新时间:2023-09-26

这就是我想做的。如果我点击更新按钮,左边的文本将是一个输入框,如下所示:点击更新按钮,左边的文本将是一个输入框

但是真正发生的是左边的所有文本都被INPUT框取代了,图片在这里:所有左侧文字均受影响

如何使用唯一id之类的?抱歉,我是jQuery的新手。你能解释一下我如何编辑MySQL上受影响的表吗?

代码:

<table class="table no-margin">
              <thead>
              <tr>
                <th width="250px">Category</th>
                <th width="20px"> </th>
                <th width="20px"> </th>
              </tr>
              </thead>
              <tbody>
              <?php 
                while ($rows = mysql_fetch_array($result)) {
                  $tcategory = $rows['vCategory'];
                  $cid = $rows['id'];
              ?>
              <tr>
                <td>
                <?php echo '<div class="editable">'. $tcategory .' </div>'; ?>
                </td>
                <td><button id="edit" class="btn btn-block btn-xs btn-success"> Update</button> </td>
                <td><button class="btn btn-block btn-xs btn-danger">  Delete</button> </td>
                <?php
                }
                ?>
                <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
                <script>
                  $("#edit").click(function() {
                    var $this = $(this);
                    if($this.attr('editing') != '1') {
                      $this.text('Save').attr('editing', 1);
                      $(document).find('.editable').each(function() {
                        var input = $('<input class="editing" />').val($(this).text());
                        $(this).replaceWith(input);
                      });
                    }else {
                      $this.text('Update').removeAttr('editing');
                      $(document).find('input.editing').each(function() {
                        var div = $('<div class="editable" />').text($(this).val());
                        $(this).replaceWith(div);
                      });
                    }
                  });
                </script>
                </tr>
                <form>
                <tr>
                  <td><input type="text" class="form-control" name="addCategory" placeholder="Enter New Category"></td>
                  <td><input type="submit" class="btn btn-block btn-sm btn-success" value="Add"></td>
                </tr>
                </form>   
              </tbody>
            </table>

在所有编辑按钮中添加相同的类。删除编辑id。记住id是唯一的。试试这样做:

https://jsfiddle.net/v2bxdttz/

使用

$(this).closest('tr').find('.editable').each(function() {
不是

 $(document).find('.editable').each(function() {