我有一个名为分支的数据表,它有三列:名称、代码和电子邮件(以及隐藏给用户的ID列)。它最初在顶部有一个编辑按钮,只有在单击一行后,用户才能单击该按钮打开一个填充了字段的对话框并对其进行编辑。然而,现在我需要更改它,以便每行都有自己的编辑按钮,因此无需先单击该行。
所以现在我对DataTable中的每一行都有一个编辑按钮,但是除了索引号之外,我不能传递该特定行的数据。相关的代码块如下(除非我遗漏了什么,否则请告诉我是否有):
var txtName2 = $("#txtName2"); //For Update
var txtCode2 = $("#txtCode2");
var txtEmail2 = $("#txtEmail2");
var dialog;
var tblBranch = $("#tblBranches");
var branchList;
var selectedIndex;
branchList = response.branches;
var data = { "aaData": [] };
$.each(response.branches, function (i, item) {
data.aaData.push({
"id": item.id,
"name": item.name,
"code": item.code,
"email": item.email,
"action": "<button> class='btnUpdate' type='button' onClick='testUpdateButton(" + i + ")'</button>"
});
});
function testUpdateButton(index, name, code, email) {
//alert(index);
selectedIndex = tblBranch.row(this).index();
var selectedName = tblBranch.row(index).name;
var selectedCode = tblBranch.row(index).code;
var selectedEmail = tblBranch.row(index).email;
//alert(name);
onBtnUpdateClicked(index, name, code, email);
}
function onBtnUpdateClicked(index, name, code, email) {
if (branchList != null && branchList.length > 0) {
var selectedItem = branchList[selectedIndex];
txtName2.val(selectedItem.name);
txtCode2.val(selectedItem.code);
txtEmail2.val(selectedItem.email);
dialog = $("#dialog-form-update").dialog("open");
}
}
当我只在按钮处传入索引号“i”而不是姓名、代码或电子邮件时,testUpdateButton下的警报(index)会显示所选行的正确索引号,因此确认它可以获得索引号,但不能获得其他三列(警报(name)不显示任何内容)。
所以我尝试在按钮上传递所有四个字段,如下所示:
"action": "<button> class='btnUpdate' type='button' onClick='testUpdateButton(" + i + ", " + item.name + ", " + item.code + ", " + item.email + ")'</button>"
但它只给我一个错误:"UncatetSyntaError:缺失)后参数列表",当我在Chrome检查页面。我看不到缺失的括号应该在哪里。
基本上,我可以获取索引号,但无法使用它来获取相应的名称、代码和电子邮件。
作为参考,这里有一个与我之前的解决方案最接近的函数——这将传递所有行数据,并在我单击行本身的任何位置时加载带有填充输入字段的编辑对话框。它是从以前的“首先单击行”版本修改的,尽管我只是添加了onBtnUpdateCl的函数。不理想,但至少它做了它应该做的事情。
$("#tblBranches tbody").on('click', 'tr', function () {
selectedIndex = tblBranch.row(this).index();
onBtnUpdateClicked();
});
任何帮助都非常感谢。
由于您可以获取row的索引,因此您可以使用它来获取其他值。尝试如下
function testUpdateButton(index){
//alert(index);
selectedIndex = index;
var name=$("table tr").eq(index).children('td').eq(1).text();
var email=$("table tr").eq(index).children('td').eq(2).text();
alert(name);
alert(email);
onBtnUpdateClicked(index, name, email);
}
获得这些值的一个复杂的小提琴是https://jsfiddle.net/shoaibakhter/atpgdofh/19/.这不是一个完整的解决方案,但是是的,这将帮助您获得其他值,您可以将其传递给您的onBtnUpdateCl的函数。您必须根据您的表结构更改函数,并且在您的onBtnUpdateCl的使用这些值如下-
function onBtnUpdateClicked(index, name, email) {
if (branchList != null && branchList.length > 0) {
var selectedItem = branchList[index];
txtName2.val(name);
txtEmail2.val(email);
dialog = $("#dialog-form-update").dialog("open");
}
}
希望这对你有帮助。