我在保存新行时遇到问题。当我点击添加人我能输入数据时,我不知道如何保存并添加新行。
我知道我必须为保存按钮设置一个功能,但我仍然坚持如何使其工作。我试了好几次但没有用。
var isNewLineToggled = false;
var isAscending = {
name : false,
lastName: false,
dob: false
};
$(".main").append("<input placeholder='search by name' class='search'/><br/><br/>")
$(".main").append("<button onclick=addPerson()>add a person</button><br/><br/>")
var table = $(".main").append("<table></table>");
var thead = '<thead><tr></tr></thead>';
table.append(thead);
var header = [
{ title: 'Name', sortBy: 'name'},
{ title: 'Last Name', sortBy: 'lastName'},
{ title: 'Date of birth', sortBy: 'dob'}
].map(
function(header) {
var sortButton = '<button id="' + header.sortBy + '" onclick=sortRows("'+ header.sortBy + '")>/\\</button>';
$('thead').append('<th>' + header.title + ' ' + sortButton + '</th>');
}
)
var tbody = "<tbody></tbody>";
var data = [ {name: 'Peter', lastName: 'Petterson', dob: '13/12/1988'},
{name: 'Anna', lastName: 'Jones', dob: '06/02/1968'},
{name: 'John', lastName: 'Milton', dob: '01/06/2000'},
{name: 'James', lastName: 'White', dob: '30/11/1970'},
{name: 'Luke', lastName: 'Brown', dob: '15/08/1999'}
];
$('.search').change(function(event) {
searchedName = event.target.value;
})
table.append(tbody);
data.map(
function(row, i) {
$('tbody').append(
'<tr><td>' + row.name +
'</td><td>' + row.lastName +
'</td><td>' + row.dob +
'</td><td><button onclick=editRow('+i+')>edit</button><button>delete</button></td></tr>'
)
}
)
var editableRow = "<td><input/></td><td><input/></td><td><input type='date'/></td><td><button onclick=saveRow()>save</button></td>";
var addPerson = function() {
isNewLineToggled = !isNewLineToggled;
if (isNewLineToggled) {
$('tbody').prepend('<tr>' + editableRow + '</tr>')
} else {
$('tbody > tr:first-child').remove();
}
}
var editRow = function(rowNumber) {
var name = $('tbody > tr:nth-child('+(rowNumber + 1)+') > td:first-child').text();
var lastName = $('tbody > tr:nth-child('+(rowNumber + 1)+') > td:nth-child(2)').text();
var dob = $('tbody > tr:nth-child('+(rowNumber + 1)+') > td:nth-child(3)').text();
$('tbody > tr:nth-child('+(rowNumber + 1)+')').html(editableRow2);
$('tbody > tr:nth-child('+(rowNumber + 1)+') > td:first-child > input').val(name);
$('tbody > tr:nth-child('+(rowNumber + 1)+') > td:nth-child(2) > input').val(lastName);
}
答案 0 :(得分:0)
您可以添加这样的行,两个小的更改:
$(".main").append("<button class='add'>add a person</button><br/><br/>")
删除内联事件处理程序,不需要它。你的功能可能是:
$('body').on('click','.add', function() { //you will need event delegation, because of dynamically added elements
isNewLineToggled = !isNewLineToggled;
if (isNewLineToggled) {
$('tbody').prepend('<tr>' + editableRow + '</tr>')
} else {
$('tbody > tr:first-child').remove();
}
});
由于未定义editableRow变量,我只使用了一个带文本的单元格进行演示:
https://jsfiddle.net/2c97auey/1/
P.S。您的editableRow应该具有输入(s)值,正确放置在单元格中。不应该太难。