Jquery可满足所有单元格而不是行

Jquery contenteditable for all cells not rows

本文关键字:单元格 可满足 Jquery      更新时间:2023-09-26

我通过使用JS和Jquery添加行和列来创建一个表。这是我的代码:

 function AddColumnToDataTable(){
      $('#tableHeader').append("<th> Header </th>").attr("contenteditable", true); 
// Add a new ColumnHeader and set the property "editable"
    }
    function AddRowToDataTable(){
      var count = $('#tableHeader').find("th").length; 
// Get the count of Columns in the table
      var newRow = $('#tableBody').append("<tr></tr>"); 
// Add a new Row
      for(var i = 0; i < count ; i++){
          newRow.find('tr').last().append("<td> Content </td>").attr("contenteditable", true); 
// Fill the cells with a default text and set the property "editable"
      }
    }

所以我的问题是,我怎么写代码,每个单元格是可编辑的?现在,当我点击时,整行都是可编辑的?每个单元格都应该有这个属性。

我找到了一个可以帮助的代码:

//$('table th:nth-child(4)').attr("contenteditable", true)

这使得第4页眉/单元格可编辑,但我怎么能使用它,每个新创建的页眉/单元格是第n个子?

jQuery append函数不返回新的[appended]元素,而是返回被附加到的元素,因此代码中出现了错误。无论如何,在追加字符串中手动设置属性更简单。所以,改变这一行:

newRow.find('tr').last().append("<td> Content </td>").attr("contenteditable", true); 

:

newRow.find('tr').last().append("<td contenteditable="true"> Content </td>")

应该可以了

$('table td').last().attr("contenteditable", true);