如何使用 StringBuilder 编辑动态创建的 HTML table

How to edit dynamically created HTML table using StringBuilder

我使用 StringBuilder 创建了一个动态 HTML table。但是当我试图将它的单元格值传递给 jQuery Ajax 调用时,我没有得到正确的值。聚焦后如何获取单元格值?

这是确切的代码片段:

Dim table as new StringBuilder()
For each item in strategy

table.AppendLine(String.Format(“<td>{0}</td>”,item.id);

table.AppendLine(“<td>{0}</td>”,item.price);

table.AppendLine(“<td contenteditable=“”true”” onfocusout =“SaveVal({0},{1})””>{1}</td>”,item.id, item.cellvalue );

Next

Return table.tostring ();

.aspx 文件中的 SaveVal Jquery 方法:

function SaveVal(id,cellvalue){
$.ajax({
type:"POST",
url:"Maintenance.aspx/SaveVal",
contentType:"application/json;charset=utf-8",
dataType:"json",
data: JSON.stringify({
ids: id,
val:cellvalue
}),
async:false,
success:function(response){
alert("Value Saved");
}
});
}

我想在聚焦后获取此内容 editable 单元格值。 SaveVal(id,cellvalue) 函数在 jQuery Ajax 调用中定义,我想传递这两个参数 idcellvalue 这是单元格的最终值 - 如果有没有编辑当时存在的值,如果我们编辑并输入新值,那么新值将被传递。

首先摆脱内联 javascript,这不再是最佳做法。

接下来,为您的 table 提供一个 ID 或其他识别方式(在我的示例中,我将使用“MyTable”的 ID)。

然后,正如您所指出的 jquery 正在使用中,我们将分配一个 jquery 事件处理程序。

vb.net

Dim table as new StringBuilder()
For each item in strategy

'give this an identifiyer to explicitly find it in jQuery/javascript
table.AppendLine(String.Format("<td data-id>{0}</td>",item.id);

table.AppendLine("<td>{0}</td>",item.price);

'no more inline javascript 
table.AppendLine("<td contenteditable=""true"">{1}</td>",item.id, item.cellvalue );

Next

Return table.tostring ();

jquery/javascript

$(document).ready(function(){
    /*Event handler for foucusout content edtitable cells in MyTable*/
    $("#MyTable [contenteditable=true]").on("focusout", function(){ 
       //Get ID
       let id = $(this).prevAll("[data-id]:first").text();
       //Get value of this cell
       let cellvalue = $(this).text();
       //Call your function, or just put its contents here
       SaveVal(id,cellvalue);
    });
});

function SaveVal(id,cellvalue){
  $.ajax({
    type:"POST",
    url:"Maintenance.aspx/SaveVal",
    contentType:"application/json;charset=utf-8",
    dataType:"json",
    data: JSON.stringify({
      ids: id,
      val:cellvalue
  }),
    async:false,
    success:function(response){
      alert("Value Saved");
    }
  });
}