jQuery replaceWith Inside Loop故障

时间:2016-09-22 04:47:57

标签: javascript jquery html mysql css

所以这就是我想做的事情。如果我点击更新按钮,左侧的文字将是一个INPUT框,如下所示: Click the update button and the text on the left will be an input box

但是真正发生的是左侧的所有文字都被INPUT框替换,图片在这里: all text left side is affected

如何使用唯一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>

1 个答案:

答案 0 :(得分:0)

将相同的课程放在所有编辑按钮中。删除编辑ID。记住ID是唯一的。尝试这样的事情:

https://jsfiddle.net/v2bxdttz/

使用

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

而不是

 $(document).find('.editable').each(function() {
相关问题