[英]Deleting list of elements in Javascript
考慮下面的代碼。 在"videos_list"
元素內部, i
有一個在“ couple”變量中獲得的元素列表。 我正在嘗試刪除所有具有"ai"
與"list_couple"
不同的屬性的元素(以測試我只放置了一個元素)。 問題是,當他找到元素時,他不會刪除找到的元素之后的其他元素。
舉例說明這個想法:考慮列表("x", "r", "t", "b", "h", "p")
和id="t"
。
他在做什么("_", "_", "t", "b", "h", "p")
。
他應該這樣做("_", "_", "t", "_", "_", "_")
或("t")
。
找到元素后,為什么“ i”的值在0和1之間切換? 我在示例中通過alert()函數看到了這一點。 我認為,問題出在“ while”循環中。
var clicked = 0;
var interval = setInterval(function( ) {
var list_couple = new Array("2583521"),
clicks = 1,
videos = document.getElementById( "videos_list" ),
couple = videos.getElementsByTagName( "a" );
var i = 0;
while( i < couple.length ) {
var flag = 0;
//alert(i);// To see the value of the i.
for(j = 0; j < list_couple.length; j++) {
if((couple[i].getAttribute( "ai" )) == list_couple[j]) {
flag = 1;// Element found.
i++;
break;
}
}
if( !flag ) {
videos.removeChild( couple[i].parentNode );
}
}
document.getElementById('btnMoreVideos').click();// Click on the button.
clicked++;
if(clicked >= clicks) {
clearInterval( interval );
}
}, 1000);
我究竟做錯了什么?
我認為您的問題是因為i ++應該超出您的for語句。
while( i < couple.length ) {
var flag = 0;
//alert(i);// To see the value of the i.
for(j = 0; j < list_couple.length; j++) {
if((couple[i].getAttribute( "ai" )) == list_couple[j]) {
flag = 1;// Element found.
//i++;
break;
}
}
if( !flag ) {
videos.removeChild( couple[i].parentNode );
}
i++;
}
更新我剛剛回顧了這個問題,並意識到您的代碼片段還有另一個問題(在@nicosierra的答案中也存在)。 在刪除節點時, couple
節點列表將作為實時列表更新。 這將導致couple.length
減小並且一些節點將被跳過。
我建議您考慮使用forEach
和indexOf
如果您可以依靠它們對節點和數組迭代的支持。 這只是遍歷所有錨的couple
,如果該元素有一個匹配ai
屬性,那么它會從刪除元素videos
父。 迭代時更新列表無關緊要
var list_couple = ["2583521"],
videos = document.getElementById( "videos_list" ),
couple = videos.getElementsByTagName( "a" );
Array.prototype.forEach.call(couple, function(node) {//iterate node list
if(list_couple.indexOf(node.getAttribute( "ai" )) >= 0) {
videos.removeChild( node.parentNode );
}
});
或者,您也可以向后迭代節點
for (var i = couple.length-1; i >= 0; i--) {
if(list_couple.indexOf(couple[i].getAttribute( "ai" )) >= 0) {
videos.removeChild( couple[i].parentNode );
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.