首页 > 解决方案 > 如何在将参数发送到函数时删除单击的行?昏死

问题描述

我对服务删除有些复杂。我有删除服务器上服务的功能,但我必须重新加载页面才能更新表。我找到了如何通过单击绑定删除行的方法,但存在问题,因为我只能从服务器中删除行或获取删除服务的 ID,而不是两者。:/

这是删除服务器上的服务但不删除表格行的代码示例。

HTML:

<table id="serviceView" class="fixed_header" border: 1>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Adress</th>
                    <th>Notification</th>
                </tr>
            </thead>
            <tbody  data-bind="foreach: services">
                <tr>
                    <td data-bind="text: name"></td>
                    <td data-bind="text: address"></td>
                    <td data-bind="text: serviceId"></td>
                    <td ><button data-bind="click: $parent.DeleteService.bind(this, serviceId)">Remove</button></td> 
                </tr>
            </tbody>

        </table>

JS:

self.services = ko.observableArray([]); 
    self.lastCheck = ko.observable();
    $.getJSON("http://localhost:55972/api/status", function (data) {
        self.services(data.services);
        self.lastCheck = data.lastCheck;
    });    //////This is loading data to the table from server

    self.DeleteService = function (serviceId) {
        $.ajax({
            type: "GET",
            url: "http://localhost:55972/api/services/remove/" + serviceId,
        }).done(function () {
            self.services.remove(serviceId)
        })

    };  

这是删除表格行的代码示例

当我像这样使用点击绑定时:

<button data-bind="click: $parent.DeleteService">Remove</button>

并将删除功能更改为:

self.DeleteService = function (serviceId) {
        self.services.remove(serviceId)
        $.ajax({
            type: "GET",
            url: "http://localhost:55972/api/services/remove/" + serviceId,
        }).done(function () {
            // here I want to remove row but i doesnt goes here without service ID.
        })

    };

它删除了行,但我在 URL 中得到了 [object, object] 的 serviceId。

你能帮我吗?我想使用 jquery 来更新表,但是当我可以使用淘汰赛时,这对我来说似乎不必要地复杂。

我知道解决方案并不难,但我就是无法解决它..... -_-

我很抱歉花时间在这些废话上,但这是我的第一个真正的项目,此时我非常绝望,因为我有很多事情要做,而且我被困在这上面。

标签: javascriptknockout.jshtml-table

解决方案


在你的 Js 代码中,你可以试试这个:

self.services = ko.observableArray([]); 
    self.lastCheck = ko.observable();
    $.getJSON("http://localhost:55972/api/status", function (data) {
        self.services(data.services);
        self.lastCheck = data.lastCheck;
    });    //////This is loading data to the table from server
var serviceIdRemoved; 
    self.DeleteService = function (serviceId) {
serviceIdRemoved = serviceId; // now you can do whatever you need more with this value
        $.ajax({
            type: "GET",
            url: "http://localhost:55972/api/services/remove/" + serviceId,
        }).done(function () {
            self.services.remove(serviceId)
        })

    }; 

通过这种工作方式,您可以使用变量的内容并且不会丢失它。此外,如果你得到 [Object, Object],你可以:

console.log(serviceId) // to see the content in the console.

JSON.stringify(data) //to see the content in html

此来源可以帮助您更好地理解它。


推荐阅读