2012-05-18 73 views
3

我已經查看了幾個可編輯的表格插件,但我不確定它們是否真的有必要滿足我的需求。我想要做的就是點擊一個td元素,獲取當前值,然後將td html更改爲一個輸入+按鈕,當按下該按鈕時,移除輸入和按鈕並將新文本放入td中。這是我所擁有的,它根本不工作。當你點擊一個td時,整個表將消失並被一個輸入替換。jQuery用戶可編輯表格單元格

這裏是JS:

var selectedObj; 

    $('td').click(function(e){ 
     // Handle the click 

    if ($('#currentInput').length == 0) 
    { 
      selectedObj = $(this); 
     var currentValue = $(this).text(); 
     var newValue = currentValue; 

     $(this).html("<input id='currentInput' type='text' value='"+currentValue+"'/> <button onclick='setNewValue()'>Set</button>"); 
    } 

    }); 
    function setNewValue() 
    { 
      var newValue = $('#currentInput').val(); 

     selectedObj.html(''); 
      selectedObj.text(newValue); 
    } 

和HTML:

<p> 
<table id='transitTable' border="0" cellspacing="2" cellpadding="2" class='display' width="400"> 
<tr id='1'> 
<td class="etsHeader etsLeft">H1</td> 
<td class="etsHeader etsLeft">H2</td> 
<td class="etsHeader etsLeft">H3</td> 
<td class="etsHeader etsLeft">H4</td></tr> 
<tr id='2'> 
<td class="etsValue etsOdd etsLeft">R1</td> 
<td class="etsValue etsOdd etsLeft">R1</td> 
<td class="etsValue etsOdd etsLeft">R1</td> 
<td class="etsValue etsOdd etsLeft">R1</td></tr> 
<tr id='3'> 
<td class="etsValue etsEven etsLeft">R2</td> 
<td class="etsValue etsEven etsLeft">R2</td> 
<td class="etsValue etsEven etsLeft">R2</td> 
<td class="etsValue etsEven etsLeft">R2</td></tr></table></p> 

回答

2

這是因爲您正在使用input標籤是在這方面無效更換td

違規代碼

$(this).html("<input id='currentInput' type='text' value='"+currentValue+"'/> <button onclick='setNewValue()'>Set</button>");

嘗試.append()td或者在另一個標籤包住td值。

+0

當輸入框中向我們展示了它填充了所有TD標籤的所有文本。任何想法發生了什麼? –

4

你爲什麼不嘗試CONTENTEDITABLE = TRUE,

檢查它here

+0

+1,因爲這是一個可行的解決方案,因爲在閱讀您的答案之前我不知道這一點。很酷,但不適用於一些較舊的瀏覽器。 – Marc

+0

這是一個好主意,但不適合我的需求,因爲我需要它在Internet Explorer 8中工作。 –

+0

+1不知道。 –