c# - 如何使用 StringBuilder 编辑动态创建的 HTML 表
问题描述
我使用 StringBuilder 创建了一个动态 HTML 表。但是当我试图将它的单元格值传递给 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");
}
});
}
我想在聚焦后获得这个内容可编辑的单元格值。SaveVal(id,cellvalue)
函数是在 jQuery Ajax 调用中定义的,我想传递这两个参数id
,cellvalue
这是单元格的最终值——如果没有编辑则现有值,如果我们编辑并键入新值,则将传递新值。
解决方案
首先摆脱内联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");
}
});
}
推荐阅读
- javascript - 在传单中单击标记时不生成地图单击事件
- sql - 在 AZure 数据工厂中映射日期
- python - 如何在 docx 文档中创建的表格中提取文本数据
- javascript - Angular 7 在 contenteditable div 中移动插入符号
- android - Imageview裁剪机制最佳方法
- regex - 我的正则表达式中缺少什么来解决这个看似非常简单的问题
- servicestack - SharpScript .ss 文件可以连接到数据库,但相同的代码在提供给本地网络浏览器时不起作用?
- sql - 如何在 DECODE 中创建两个条件
- android - 更改模拟的前置摄像头图像?
- python - 如何在python中为D盘中的文件夹提供正确的路径