Javascript 如何停止在jQuery的每个循环中添加更多具有相同索引的项?

Javascript 如何停止在jQuery的每个循环中添加更多具有相同索引的项?,javascript,jquery,Javascript,Jquery,如何停止在jQuery的每个循环中添加更多具有相同索引的项 我有以下代码: var arr = data.errors; var oneIndexIsEnough = ''; $.each(arr, function(index, value) { if (value.length != 0) { if (oneIndexIsEnough != index) { $("#" + index).after('<span class=

如何停止在jQuery的每个循环中添加更多具有相同索引的项

我有以下代码:

var arr = data.errors;
var oneIndexIsEnough = '';

$.each(arr, function(index, value)
{
    if (value.length != 0)
    {

        if (oneIndexIsEnough != index) {
            $("#" + index).after('<span class="text-error validation-error-inline">' + value + '</span>');
            oneIndexIsEnough = index;
        } else {
            //
        }

    }
});
但是我不希望有5条错误消息,我只希望有这2条

   username   |  username could contain only letters 


当索引的名称重复时,如何停止并跳转到下一个名称索引?

我认为问题在于您只存储找到的最后一个索引,如果您使用数组存储处理过的索引,然后检查它们是否已经在索引中呢

var arr = data.errors;
var processed = [];

$.each(arr, function(index, value) {
    if (value.length != 0) {
        if (processed.indexOf(value.index) == -1) {
            // process value.message
            processed.push(value.index);
        } else {
            //
        }
    }
});
如果阵列的布局类似于:

var arr = [
    {
        index: 'username',
        message: 'username could contain only letters'
    }
];

尝试检查元素是否已将文本错误范围作为其第一个同级

像这样的

//I select the first sibling of your index with the class "text-error"
if (!$("#" + index).siblings('span').eq(0).hasClass("text-error")) 
{
    $("#" + index).after('<span class="text-error validation-error-inline">' + value + '</span>');
}

通过这种方式防止同一元素出现多条错误消息应该比跟踪索引更容易。

为什么不制作数组的压缩副本呢?@Diodeus数组的压缩副本?@XaxD,用于DOM,不用于我的JSON数组。我需要某种中断,例如username包含两条消息,当每条消息经过tehm I时我收到两条信息。但我只想获得第一个索引,然后移动到下一个索引,例如电子邮件。我尝试了你的解决方案,但它仍然显示所有3个错误,而不仅仅是我的用户名的第一个错误;哦,我们被索引变量的含义弄糊涂了,我更新了我的答案…不,它仍然在页面上显示所有错误。我想在第一次添加后停止向索引用户名添加错误消息,然后转到下一个名为email的索引,并在那里添加错误消息。Hmm。我得到的错误类型错误:$..同级不是一个函数
var arr = [
    {
        index: 'username',
        message: 'username could contain only letters'
    }
];
//I select the first sibling of your index with the class "text-error"
if (!$("#" + index).siblings('span').eq(0).hasClass("text-error")) 
{
    $("#" + index).after('<span class="text-error validation-error-inline">' + value + '</span>');
}