2016-09-17 2 views
1

여기에 select 요소와 몇 가지 옵션 요소가 있습니다. foreach 루프를 실행하여 모든 옵션 요소를 삭제하려고합니다. 그러나 처음 두 요소 만 제거되고 있습니다.이 오류는 무엇입니까? 암호?select 태그에서 모든 옵션을 제거합니다

<!DOCTYPE html> 
<html> 
<body> 
<p id='item'></p> 
<form> 
remove all from fruit list: 
<br> 
<select id="mySelect" size="4" class='myclass' onChange='myFunction(this.className);'> 
    <option id='for_apple'>Apple</option> 
    <option>Pear</option> 
    <option>Banana</option> 
    <option>Orange</option> 
</select> 



<script> 
let select_item = document.getElementById('mySelect'); 
let options=select_item.getElementsByTagName('option'); 
console.log('length is : '+options.length); 
Array.prototype.forEach.call(options,(elem,index,arr) => { 

    console.log(options.length); 
    select_item.removeChild(elem); 
}); 
</script> 

</body> 
</html> 
+1

내 생각 엔 options' 업데이트가 살고있는'이다 :이 개 요소를 제거한 후, 그 길이가 4-2 ==이되고, 그래서 루프가 멈 춥니 다. – melpomene

+0

'select_item.innerHTML = "";'사용하기 : while (options.length) select_item.removeChild (options [0]);' –

답변

3

Nodelists는 "라이브"이므로 반복 할 때 길이가 변경되고 루프가 중지됩니다.

[].slice.call(options).forEach((elem,index,arr) => { 
    console.log(options.length); 
    select_item.removeChild(elem); 
}); 

을 :

이 솔루션은 뒤로

let select_item = document.getElementById('mySelect'); 
let options = select_item.getElementsByTagName('option'); 

for (var i=options.length; i--;) { 
    select_item.removeChild(options[i]); 
} 
+0

살고 길이 속성도 업데이트해야한다면 안된다. ? 그리고 조건을 확인하지 않으면 무한 루프가 생성됩니까? –

+2

forEach 루프를 시작하면 길이를 검사하고 4 개 요소를 반복한다고 가정합니다. 그런 다음'options [0]'에서 첫 번째 요소를 제거하고 노드 목록을 업데이트합니다. 이제 세 개의 요소가 있는데, 첫 번째 요소는'[0]'에 있습니다. '[1]'에서 두 번째 요소를 얻고 nodeList를 다시 업데이트하면 이제는 [0]과 [1]에 두 개의 요소가 있습니다. forEach 루프는 이제 세 번째 요소 인'[2] '를 얻으려고 시도하지만 nodeList가 자체적으로 업데이트됨에 따라 해당 위치에 요소가 없습니다. – adeneo

+0

감사합니다 .. 나는 for 루프에 관한 또 다른 질문이 있습니다, 그것은 어떤 제약이 없습니다 .. 어떻게 멈출지를 어떻게 알 수 있습니까? –

1

당신은 그것을 forEach를 호출하기 전에 대신

let options = document.querySelectorAll('#mySelect option'); 
+0

또한 노드리스트를 반환하고 모든 노드리스트가 라이브라고 들었습니다 ... –

+1

@ AL-zami [querySelectorAll] (https : //developer.mozilla. org/ko-kor/docs/Web/API/Document/querySelectorAll)는 라이브가 아닌 노드 목록을 반환합니다 .. – Anirudha

+0

ok thanks :) ... https://developer.mozilla.org/en-US/docs/ 웹/API/문서/querySelectorAll –

0

는 또 다른 옵션은 convert the NodeList into an array하는 것 이외의 라이브 querySelectorAll을 사용할 수 있습니다 반복하는 것입니다 이미 ES2015 syn을 사용하고 있으므로 세금은 그냥 작업을 수행 할 spread syntax를 사용

[...options].forEach((elem,index,arr) => { 
    console.log(options.length); 
    select_item.removeChild(elem); 
}); 

또는 Array.from

Array.from(options).forEach((elem,index,arr) => { 
    console.log(options.length); 
    select_item.removeChild(elem); 
}); 
관련 문제