[英]how to remove searched item and remove that item from array?
我有一個搜索字段,在該字段中我可以搜索一個項目。 然后,我必須將其刪除,但不幸的是,我不t know how I can remove that item. Please, could you help me with that. I tried the following: If
t know how I can remove that item. Please, could you help me with that. I tried the following: If
t know how I can remove that item. Please, could you help me with that. I tried the following: If
ID of
currentRobot is equal to
當前id`然后刪除該項目,但我想這是不完全正確,因為它不工作 我的密碼
$(document).ready(function(){
var currentRobot=null;
for( var i=0; i<robots.length; i++){
var robot = document.createElement('div');
robotsContainer.appendChild(robot);
robot.className='whole-block';
robot.setAttribute('id', robots[i].id);
robot.innerHTML += "<img src='" + robots[i].avatar + "'>";
robot.innerHTML += "<h3>" +robots[i].first_name + "</h3>";
robot.innerHTML += "<h3>" +robots[i].last_name + "</h3>";
robot.innerHTML += "<p>" +robots[i].email + "</p>";
robot.innerHTML += "<p>" +robots[i].gender + "</p>";
robot.innerHTML += "<p>" +robots[i].friends + "</p>";
}
console.log(value)
value.onkeyup = function(e){
currentRobot=e.target.value;
var robots = document.querySelectorAll("div[id]:not([id='"+ this.value +"']):not([id='robotsContainer'])");
for(var i = 0; i < robots.length; i++ ){
if(this.value==""){
robots[i].style.display="block";
} else {
robots[i].style.display="none";
}
};
};
var button= document.getElementById('button');
button.addEventListener('click', function(e){
e.preventDefault();
for(var i = 0; i < robots.length; i++){
if (robots[i].id === currentRobot) robots.splice(i, 1);
}
}, false);
});
您正在協助currentRobot
currentRobot=e.target.value;
然后您在比較它的價值
if (robots[i].id === currentRobot) robots.splice(i, 1);
我的直覺是currentRobot
和robots[i.id
]的類型不同。 在比較之前嘗試添加
console.log( currentRobot, robots[i].id);
為了使此比較有效,它們必須具有相同的數據類型。
另外,請記住,數組的第一個索引是0
而不是1
。
不知道全球robots
是什么,我們必須猜測。
robots
是一個真正的數組 如果robots
是真正的JavaScript數組,則從數組中刪除應該使用splice
,但是:
因此,您的代碼可以按以下方式處理:
因此,替換為:
if (robots[i].id === currentRobot) robots.splice(i, 1);
..with:
if (robots[i].id === currentRobot) {
var node = document.getElementById(currentRobot);
node.parentNode.removeChild(node);
robots.splice(i, 1);
break; // and exit loop!
}
robots
是HTML集合 如果您的全局變量robots
是HTML集合,則它類似於數組,但不是真正的數組,因此您無法在它們上應用splice
。 相反,您必須使用DOM方法。
因此,請替換為:
if (robots[i].id === currentRobot) robots.splice(i, 1);
..with:
if (robots[i].id === currentRobot) {
robots[i].parentNode.removeChild(roots[i]);
break; // and exit loop!
}
您需要退出循環,因為在變異的HTML集合上繼續循環會很麻煩,這也是不必要的,因為您希望以任何方式只匹配一個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.