循环DOM元素

时间:2011-11-04 16:24:49

标签: javascript jquery

因此,这是我的功能,如果您点击表单的某个部分,它会从列表中删除人员:

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.");
            }
        });
    });
}

}

所以我不确定如何才能让它发挥作用。

3 个答案:

答案 0 :(得分:1)

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.");
                }
            });
        });
    }
}

答案 1 :(得分:1)

基本上,你需要引入一个闭包来捕获每次循环的i的值。使用$.each()将为您引入一个闭包(类似于此)

function ParticipantsDeleteClick(model, url) {
    $.each(model.Participants, function(i,v) {
        $("#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.");
                }
            });
        });
    });
}

答案 2 :(得分:0)

这里有3个范围级别:

  1. 循环范围
  2. 点击处理程序范围
  3. ajax成功处理程序范围
  4. 因此,您需要为每个范围保留并传递变量。 .bind()方法允许您将参数传递给外部作用域的回调,context参数允许您将参数传递给AJAX成功回调。所以:

    $.each(model.Participants, function(index, participant) {
        var data = { index: index, participant: participant };
        $('#delete' + index).bind('click', data, function(evt) {
            // at this stage evt.data will point to what the data variable was pointing
            // from the outer scope but at the moment this handler was bound
            $.ajax({
                url: url,
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                data: JSON.stringify({ id: evt.data.participant }),
                context: evt.data.index,
                success: function (result) {
                    // since we have used the context parameter at this stage
                    // this will point to this parameter which is simply the index
                    result ? $('#participant' + this).remove() : alert('Delete failed');
                },
                error: function () {
                    alert('Could not get a response from the server.');
                }
            });
        });
    });
    

    或者将其分解为单独的函数以使其更清晰:

    function handleClick(evt) {
        $.ajax({
            url: url,
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify({ id: evt.data.participant }),
            context: evt.data.index,
            success: ajaxSuccess,
            error: ajaxError
        });
    }
    
    function ajaxSuccess(result) {
        result ? $('#participant' + this).remove() : alert('Delete failed');
    }
    
    function ajaxError() {
        alert('Could not get a response from the server.');
    }
    

    然后最后:

    function ParticipantsDeleteClick(model, url) {
        $.each(model.Participants, function(index, participant) {
            var data = { index: index, participant: participant };
            $('#delete' + index).bind('click', data, handleClick);
        });
    }