我正在尝试创建动态列表,因此当用户执行搜索时,它将重新填充列表。问题是我似乎无法创建一个不可变的常量来存储原始的div内容。每次调用函数时,此变量都会重新初始化。
有没有办法在不使用Cookie的情况下实现这一目标?任何帮助都是真诚的感谢。代码不完整,因为我无法通过这一步,但如果你认为我完全朝着错误的方向前进,请告诉我。
const originalList = document.getElementById('patientList')。getElementsByTagName('li'); frozen = Object.freeze(originalList);
<script>
const originalList = document.getElementById('patientList').getElementsByTagName('li');
frozen = Object.freeze(originalList);
var newList = '';
var found = false;
function filterPatients(){
var searchQuery = document.getElementById('search');
var query = searchQuery.value;
var listContainer = document.getElementById('patientList');
var patientList = listContainer.getElementsByTagName('li');
for (var i = 0; i < originalList.length; i++){
var link = patientList[i].getElementsByTagName('a');
var link = link[0].text;
/** remove whitespaces for easy comparison **/
link = link.toLowerCase();
query = query.toLowerCase();
link = link.replace(/\s/g, "");
query = query.replace(/\s/g, "");
/** check every character in query **/
if (link.length > query.length && link.substring(0,query.length) == query){
found = true;
newList += '<li>' + patientList[i].innerHTML + '</li>';
}
}
if (found == true){
listContainer.innerHTML = newList;
newList = '';
}
else{
listContainer.innerHTML = "<li>No patient by that name</li>";
}
console.log(frozen);
}
</script>
答案 0 :(得分:0)
const originalList = document.getElementById('patientList').getElementsByTagName('li').cloneNode(true);
使originalList成为元素的副本。目前,您将originalList和patientList设置为相同的元素列表,因此更改一个元素也将更改另一个元素。使用element.cloneNode(true)制作DOM元素的深层副本