javascript - 如何在将参数发送到函数时删除单击的行?昏死
问题描述
我对服务删除有些复杂。我有删除服务器上服务的功能,但我必须重新加载页面才能更新表。我找到了如何通过单击绑定删除行的方法,但存在问题,因为我只能从服务器中删除行或获取删除服务的 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 来更新表,但是当我可以使用淘汰赛时,这对我来说似乎不必要地复杂。
我知道解决方案并不难,但我就是无法解决它..... -_-
我很抱歉花时间在这些废话上,但这是我的第一个真正的项目,此时我非常绝望,因为我有很多事情要做,而且我被困在这上面。
解决方案
在你的 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
此来源可以帮助您更好地理解它。
推荐阅读
- javascript - ajax 内容调用完成后自动调整 div 大小
- ruby - Ruby ActiveRecord 批量检索新插入的记录?
- python-3.x - Python Selenium:如何在 chrome 驱动程序中使用 debugger_address 选项进行远程调试?
- slack-api - Slack 机器人可以重新共享与其共享的文件吗?
- batch-file - 如何获得使用批处理文件复制大文件(2.2 GB)的实时进度条?
- java - kafka 消费者尝试连接到随机主机名而不是正确的一个
- python - 从子流程输出中获取价值
- php - 如何在sql中获取两个给定日期之间的日期
- ruby-on-rails - 为什么捆绑器在寻找 mysql2 -v '0.4.4' --source 'https://rubygems.org/'
- java - java中的泛型方法来总结给定列表中的所有值,无论它是String,int,double