【问题标题】:How to edit dynamically created HTML table using StringBuilder如何使用 StringBuilder 编辑动态创建的 HTML 表
【发布时间】:2021-03-16 03:04:08
【问题描述】:

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

这里是确切的代码 sn-p:

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");
}
});
}

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

【问题讨论】:

  • 在您的问题中包含代码时,请始终格式化为代码。这似乎是 C# 而不是 vb.net。请更正您的标签。
  • A StringBuilder 没有 html 属性或字段,那么这怎么可能工作?请提供minimal, reproducible example,其中将包括您期望和获得的示例。
  • 另外,您已将此问题标记为jquery,但问题中与该标记无关。要么包含相关信息,要么删除标签。
  • 我认为这更像是一个 javascript 问题。服务器端似乎不需要任何东西。请显示SaveVal 方法。
  • 使用精确语法和 sn-p 编辑的代码。请帮忙!

标签: c# jquery vb.net stringbuilder


【解决方案1】:

首先摆脱内联javascript,这不再是最佳实践。

接下来,为您的表指定一个 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");
    }
  });
}

【讨论】:

  • 谢谢乔恩。我正在为 jquery 获取 cellvalue,但 data-id 给出了问题,因为它给出了“未定义”的值。 .prevAll("[data-id]")[0].text() 也不起作用。它说 .text() 未定义,不能与 .prevAll 一起使用。
  • 是的,自从我使用 jquery 以来已经有一段时间了。现已修复。
  • 谢谢乔恩。它现在按预期工作。感谢您的帮助!
猜你喜欢
  • 2011-01-26
  • 2016-09-23
  • 1970-01-01
  • 1970-01-01
  • 2013-09-21
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 2012-04-19
相关资源
最近更新 更多