gpt4 book ai didi

javascript - 遍历 DOM 元素

转载 作者:行者123 更新时间:2023-11-30 18:36:46 25 4
gpt4 key购买 nike

所以这是我的功能,如果您单击表单的特定部分,它会从列表中删除人员:

function ParticipantsDeleteClick(model, url) {
for (i in model.Participants) {
$("#delete" + i).click(function () {
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ id: model.Participants[i].Id }),
success: function (result) {
result ? $("#participant" + i).remove() : alert("Delete failed");
},
error: function () {
alert("Could not get a response from the server.");
}
});
});
}

出于某种原因,无论您点击哪个人,它总是会从列表中删除最后一个人。而且它只工作一次,因为一旦最后一个“i”被删除,其他所有点击函数都会指向具有最后一个 i 值的 dom 元素。

我不知道为什么每次我添加点击函数时它都指向循环中最后一个 i 的值。我修改了函数,添加了一个临时变量,该变量采用我的整数值,但也不起作用:

function ParticipantsDeleteClick(model, url) {
for (i in model.Participants) {
var temp = parseInt(i);
$("#delete" + temp).click(function () {
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ id: model.Participants[temp].Id }),
success: function (result) {
result ? $("#participant" + temp).remove() : alert("Delete failed");
},
error: function () {
alert("Could not get a response from the server.");
}
});
});
}

所以我不确定如何让它工作。

最佳答案

i 总是在循环中被覆盖。您需要一个闭包,例如通过使用 $.each(function(){..},或将循环体包装在自调用函数中。

function ParticipantsDeleteClick(model, url) {

$.each(model.Participants, function(i){ //The `function` creates a closure
$("#delete" + i).click(function () {
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ id: model.Participants[i].Id }),
success: function (result) {
result ? $("#participant" + i).remove() : alert("Delete failed");
},
error: function () {
alert("Could not get a response from the server.");
}
});
});
}
}

关于javascript - 遍历 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8012502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com