我正在为我的 Web 应用程序使用 C# ASP MVC、JavaScript 和 jQuery。
我目前有一个网格,您可以在其中单击一行来选择项目。单击该项目后,将有一个名为 .highlight
的 css 类来确保选择该项目。
当我选择该项目并单击按钮时,网格会刷新,这也很好。但现在我想知道如何让它在刷新页面之前重新选择相同的项目?
这是我尝试过的:
var $this = $selectedRow;
if ($this.hasClass("row-simple")){
// $(".highlight").removeClass("highlight");
$this.addClass("highlight");
}
单击按钮后,它将检查是否选择了一行并执行此 Ajax 请求。您可以在函数末尾看到我实际上正在尝试再次选择所选项目。
function StartToTravel() {
var $selectedRow = $(".highlight");
if ($selectedRow.length == 1) {
var id = $selectedRow.children(".td-dc")[0].innerText.trim();
if (id) {
$.ajax({
type: 'post',
url: appPath + '/service/StartTrip',
data: {
id: id
},
success: function (response) {
if (response.success) {
RefreshGrid();
}
$("#dialog .modal-body").html(response.message);
$("#dialog #dialog-title").html(response.title);
$("#dialog").modal("show");
},
error: function (response) {
$("#dialog .modal-body").html(msgErrorDuringRequest);
$("#dialog #dialog-title").html(errorTitle);
$("#dialog").modal("show");
}
});
var $this = $selectedRow;
if ($this.hasClass("row-simple") || $this.hasClass("highlight")) {
// $(".highlight").removeClass("highlight");
$this.addClass("highlight");
}
}
}
}
刷新功能:
function RefreshGrid() {
var numberPlate = $("#NumberPlate").val();
var url = '/Service/Grid?numberPlate='+numberPlate;
$("#Grid").load(url);
}
最佳答案
正如 mwebber 在评论中已经解释的那样,加载的网格完全替换了之前的网格,因此一旦网格被替换,您对原始网格所做的所有更改都将不存在。因此,您需要记住您想要影响哪一行,并在网格刷新后执行该修改。
自从您使用 jQuery.load 刷新网格后,您可以简单地使用 complete
回调来在完成后采取行动:
function RefreshGrid() {
// …
$("#Grid").load(url, null, reselectSelectedRow);
}
所以这会在完成后调用reselectSelectedRow
。在该回调函数中,您需要有选择逻辑:
function reselectSelectedRow() {
// get the selected row using the row index
// you might need to adjust this depending on your HTML
var selectedRow = $('#Grid tr').get(_selectedRowIndex);
if (selectedRow.hasClass("row-simple") || selectedRow.hasClass("highlight")) {
selectedRow.addClass("highlight");
}
}
现在剩下的就是确保在实际选择行时正确声明并设置 _selectedRowIndex
。正如所解释的in this question ,您可以查询父元素中元素的索引,因此我们使用它。
// declare the variable outside of the function so it exists on an outer scope
var _selectedRowIndex;
function StartToTravel() {
var $selectedRow = $(".highlight");
if ($selectedRow.length == 1) {
// store the index of the selected row
_selectedRowIndex = $selectedRow.index();
// the other AJAX stuff…
}
}
关于JavaScript 不会更改或添加 CSS 类到元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44101851/