Jquery .remove()移动索引

jquery .remove() shifting indexes

本文关键字:移动 索引 remove Jquery      更新时间:2023-09-26

我有一个名为AgentIDList2的多选项选择框。当我选择一堆选项并点击删除按钮时,我希望这些选项完全从AgentIDList2中删除。实际情况是,每次我删除一个元素,索引就会移动所以我的代码就不能工作了。关于如何解决这个问题有什么想法吗?

function remove_agents() {
var List = $('#AgentIDList2');
List = List[0]; 
selected = new Array(); 
for (var i = 0; i < List.options.length; i++) {
    if (List.options[i].selected) {
        selected.push(i);
    }
}
// Break it out like this so we don't screw up the indices and pick the wrong item
for (i=0; i<selected.length; i++) {
    List.options.remove(selected[i]);
    }
}

任何想法?谢谢!

试试这个

$('#AgentIDList2 option:selected').remove(); 

下面是一个工作示例。

function remove_agents() {
var List = $('#AgentIDList2')[0];
selected = []; 
for (var i = 0; i < List.options.length; i++) {
    if (List.options[i].selected) {
        selected.push(i);
    }
}
// Break it out like this so we don't screw up the indices and pick the wrong item
for (i=0; i<selected.length; i++) {
    List.options.remove(selected[i--]);
    }
}

稍微清理了一下,但是修复它的是手动调整for循环中的索引(i--)