签出这个小提琴。除了您的代码之外,它还使用以下代码来模仿您所针对的非常基本的表格控件版本
var cntnr = $('.tableholder');
var cntnr_height = cntnr.height();
var cntnr_top = cntnr.offset().top;
var cntnr_scrolltop = cntnr.scrollTop();
var all_rows = $('tr', cntnr)
var row_height = $(all_rows.get(0)).height();
$('.tableholder').click(function (ev) {
var t = ev.target;
if (t.tagName != 'TD' && t.tagName != 'TR')
return;
var the_row = t.tagName == 'TR' ? $(t) : $(t.parentNode)
all_rows.removeClass('current')
the_row.addClass('current');
})
$('#deselect').click(function () {
all_rows.removeClass('current');
})
$(document).click(function (ev) {
/*if ($(ev.target) != cntnr && $(ev.target).parents().filter(cntnr).length == 0 && $(ev.target).hasClass('container'))
all_rows.removeClass('current');*/
}).keydown(function (ev) {
//don't scroll if no rows are selected
if (all_rows.filter('.current').length == 0) {
return;
}
var keycode = ev.which;
if ([38, 40].indexOf(keycode) !== -1) {
ev.preventDefault();
}
else {
//we only scroll on up/down arrow
return;
}
var the_row = all_rows.filter('.current');
var next = the_row.next();
var prev = the_row.prev();
//check if reached extremes of table
if (
keycode == 40 && !next.length
|| keycode == 38 && !prev.length
)
return false;
the_row.removeClass('current');
if (keycode == 40) {
if (next.offset().top + row_height + 10 - cntnr_top > cntnr_height + cntnr.scrollTop()) {
cntnr.scrollTop(cntnr.scrollTop() + row_height);
}
next.addClass('current');
setDataFromRow(next)
}
else {
if (prev.offset().top < cntnr.scrollTop()) {
cntnr.scrollTop(cntnr.scrollTop() - row_height);
}
prev.addClass('current');
setDataFromRow(prev)
}
});
function setDataFromRow(row) {
if (!row instanceof jQuery)
row = $(row)
ip_id.val($('td:nth-child(1)', row).html());
ip_firstname.val($('td:nth-child(2)', row).html());
ip_lastname.val($('td:nth-child(3)', row).html());
ip_country.val($('td:nth-child(4)', row).html());
ip_city.val($('td:nth-child(5)', row).html());
ip_town.val($('td:nth-child(6)', row).html());
ip_gender.val($('td:nth-child(7)', row).html());
}
var curr = $("tr").eq(1);
curr.addClass("current");
/*$('#id').val('0');
$('#firstname').val('firstname');
$('#lastname').val('lastname');
$('#country').val('country');
$('#city').val('city');
$('#town').val('town');
$('#gender').val('gender');*/
var ip_id = $('#id'),
ip_firstname = $('#firstname'),
ip_lastname = $('#lastname'),
ip_country = $('#country'),
ip_city = $('#city'),
ip_town = $('#town'),
ip_gender = $('#gender');
setDataFromRow(curr);
/* your event handlers for buttons here */
请注意,此代码可能并非在所有方面都是完美的。我还没有触及您在某些方面出错的事件处理代码:DI 希望您从该代码中获得起点和方向