JavaScript不会更改或添加CSS类到元素

时间:2017-05-21 21:13:11

标签: javascript c# jquery

我正在为我的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);
}

如何确保选择上一个选定的项目?enter image description here

按下按钮后: enter image description here

当关闭弹出行未被选中时 enter image description here

1 个答案:

答案 0 :(得分:1)

正如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…
    }
}