【发布时间】:2018-08-02 16:41:48
【问题描述】:
我已经做了一张桌子。在那,我想做动态的添加、删除和更新操作。在我的代码中,我正在动态地向表中添加和删除行,现在我想通过 jQuery 编辑表行。更新功能的代码是什么?
在这里,我添加了我的 javascript 代码。
function Add() {
AddRow($("#txtName").val(), $("#txtEmail").val(), $("#txtCity").val());
$("#txtName").val("");
$("#txtEmail").val("");
$("#txtCity").val("");
};
function AddRow(name, email, city) {
var tBody = $("#tblCustomers > TBODY")[0];
row = tBody.insertRow(-1);
console.log(row);
var cell = $(row.insertCell(-1));
cell.html(name);
cell = $(row.insertCell(-1));
cell.html(email);
cell = $(row.insertCell(-1));
cell.html(city);
cell = $(row.insertCell(-1));
var btnRemove = $("<input />");
btnRemove.attr("type", "button");
btnRemove.attr("onclick", "Remove(this);");
btnRemove.val("Remove");
var btnEdit = $("<input />");
btnEdit.attr("type", "button");
btnEdit.attr("onclick", "Edit(this);");
btnEdit.val("Edit");
cell.append(btnRemove," ",btnEdit);
};
function Remove(button) {
var row = $(button).closest("TR");
var name = $("TD", row).eq(0).html();
console.log(row,name,row[0].rowIndex);
if (confirm("Do you want to delete: " + name)) {
var table = $("#tblCustomers")[0];
table.deleteRow(row[0].rowIndex);
}
};
function Edit(button) {
var row = $(button).closest("TR");
console.log(row);
var name = $("TD", row).eq(0).html();
var email = $("TD", row).eq(1).html();
var city = $("TD", row).eq(2).html();
if (confirm("Do you want to update: " + name)) {
var table = $("#tblCustomers")[0];
console.log(row,name,row[0].rowIndex);
$("#txtName").val(name);
$("#txtEmail").val(email);
$("#txtCity").val(city);
$('#button1').html("<input type='button' value='Update' onclick=update(this);> <input type='button' value='Cancel' onclick=Cancel();>");
return false;
}
};
function update(button)
{
// updation code here..
};
function Cancel()
{
$('#button1').html("<input type='button' value='Add' onclick=Add();>");
$("#txtName").val("");
$("#txtEmail").val("");
$("#txtCity").val("");
return false;
}
HTML 代码:
<form>
Name: <input type="text" id="txtName" placeholder=" Name"><br><br>
Email: <input type="text" id="txtEmail" placeholder=" Email"><br><br>
City: <input type="text" id="txtCity" placeholder=" City"><br><br>
<div id="button1"> <input type="button" id="add" onclick="Add()" value="Add Row"> </div>
</form>
<table id="tblCustomers">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>City</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
CSS:
table{
width: 60%;
margin: 20px 0;
border-collapse: collapse;
}
table, th, td{
border: 1px solid #cdcdcd;
}
table th, table td{
padding: 5px;
text-align: left;
}
【问题讨论】:
标签: javascript jquery html