2016-09-22 69 views
-1

所以這就是我想要做的。如果我點擊更新按鈕,左邊的文字會像下面的輸入框中輸入: Click the update button and the text on the left will be an input boxjQuery replaceWith內循環故障

但什麼是真正發生的事情是所有左側的文本是越來越有輸入框,形象在這裏代替: 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> 
+0

你不能對循環中的所有元素 – Ish

+0

沒事給同樣的編輯ID,但它在我的循環內我只是從我的數據庫中獲取類別列,這就是爲什麼它在循環內。 – TheTruth

回答

0

把所有的編輯按鈕,同一類。刪除編輯ID。記住ID是unique.Try是這樣的:

https://jsfiddle.net/v2bxdttz/

使用

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

代替

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

非常感謝!最後一個問題是,如何將編輯過的文本更新到數據庫的列上?對不起,在jQuery – TheTruth

+0

上使用ajax來獲取文本框中的值並更新數據庫 – Ish

+0

好吧非常感謝您的幫助! – TheTruth