开发者

Javascript loop limit to delete select list keeps changing

开发者 https://www.devze.com 2023-01-21 12:54 出处:网络
im trying to delete a HTML select list. This is what im using: var size = DID(SourceDiv + Number).options.length;

im trying to delete a HTML select list. This is what im using:

var size = DID(SourceDiv + Number).options.length;
    DeleteSelectElements(SourceDiv+Number,size);

function DeleteSelectElements(Div,Len){
    var k;
    var Length = Len
    for (k = 0; k < Length; k++) {
        DID(Div).options[k] = null;
    }
}

DID just returns the actual HTML element. The problem is that only EXACTLY hald the list is being deleted. The Len parameter is changing because it relates to size, which related to the actual length of the li开发者_C百科st. So when i delete in the function its actually changing 'Length' and never reaching the actual end of the list :s


You already discovered the problem: every time you delete an element, the length decreases, which means the number of valid indices also decreases by one. So, instead of trying to delete from 0 to Length, just continually delete the first element until the list is empty:

var e = DID(Div).options;
while (e.length > 0)
  e.remove(0);


of course it is: if you have a list of 10 things and you do delete the first 5, your iterator (k) is 5, your length is 5 so ((k < Length) == false) and it stops just keep deleting the first element instead of the 'current' element. or just loop it backwards :) for optimizations:

var blah = DID(Div).options;
for(k = Length; k > 0; k--)
{
    blah[k - 1] = null;
}


You can only delete the first element! When you delete it, second one becomes the new first... so delete Length of first elements?

function DeleteSelectElements(Div,Len){
    var k;
    var Length = Len
    for (k = 0; k < Length; k++) {
        DID(Div).options[0] = null;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消