如何解决Jquery 表选择行添加类并获取值选择行
$("#example tr").click(function() {
$(this).addClass('selected').siblings().removeClass('selected');
value = $(this).find('td:first').html();
});
$(document).on('keydown',function(e) {
e.preventDefault();
if (e.which == 38) {
$('.selected').prev('tr').addClass('selected').siblings().removeClass('selected');
$('#testidyeni').text("test");
} else if (e.which == 40) {
$('.selected').next('tr').addClass('selected').siblings().removeClass('selected');
}
});
<table class="table table-hover table-bordered table-scroll" id="example">
<thead>
<tr>
<th scope="col"> Id </th>
<th scope="col"> Aksesuar kateqoriya </th>
</tr>
</thead>
<tbody name="">
<?PHP foreach ($testcek as $olculer ) { ?>
<tr class="selected">
<th scope="row"> <?PHP echo $olculer['id']; ?> </th>
<td class="" value="<?PHP echo $olculer['id']; ?>"> <?PHP echo $olculer['aksesuaradi']; ?> </td>
</tr>
<?PHP } ?>
</tbody>
</table>
解决方法
将 .selected
类设置为新行后,它很简单。只需使用:
$('#example .selected td:first').text();
,
您可以将向上和向下箭头功能移出行选择功能。如果没有选中的行,则什么都不会发生。
请检查下面的评论示例。我添加了一些检查,看看你是在表格的顶部还是底部。
如果你想要别的东西,请告诉我
$("#example tr").click(function() {
// Exit early if already selected
if ($(this).hasClass("selected")) {
return;
}
// Remove selected class from any row
$("#example tr.selected").removeClass("selected");
// Assign selected class to clicked row
$(this).addClass("selected");
// Flag a selection change
selectionChange();
});
// This is unchanged
$(document).on('keydown',function(e) {
e.preventDefault();
// Check if no row is selected
if ($('tr.selected').length == 0 && (e.which == 38 || e.which == 40)) {
// Select first row that is not the header
$('tr:not(.header)').first().addClass("selected");
selectionChange();
// Leave the function early
return;
}
// If arrow down clicked
if (e.which == 38) {
// Move selected row up one
if ($('.selected').prev('tr').hasClass("header")) {
console.log("Don't move to header row");
} else {
$('.selected').prev('tr').addClass('selected').siblings().removeClass('selected');
selectionChange();
}
} else if (e.which == 40) { // If arrow up
// Move down a row
if ($('.selected').next('tr').length == 0) {
console.log("Do not move down if at bottom of table");
} else {
$('.selected').next('tr').addClass('selected').siblings().removeClass('selected');
selectionChange();
}
}
});
// Get value of selected row
function selectionChange() {
v = $("tr.selected td:first").text();
console.log(v);
}
tr.selected {
background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-hover table-bordered table-scroll" id="example">
<thead>
<tr class="header">
<th scope="col"> Id </th>
<th scope="col"> Aksesuar kateqoriya </th>
</tr>
<tr>
<td>1</td>
<td>Alpha</td>
</tr>
<tr>
<td>2</td>
<td>Beta</td>
</tr>
</thead>
</table>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。