function sort(type) {
//EMPTY FUNCTION IS CALLED HERE FOR REMOVING ALL PREVIOUSLY CREATED CHILD DIVS
$("#parentDiv").empty();
$.get("http://www.omdbapi.com/?s=Batman&page=2", ({ Search }) => {
Search.sort((a, b) => a[type] > b[type]);
console.log(`Sorted by: ${type}`);
console.log("movies are displayed!!");
var i;
Loop从这里开始创建div元素。
for(i=0;i<Search.length;i++){
var title=Search[i].Title;
var year=Search[i].Year;
父div包含其中存在h2和p的子div。
var parentDiv=document.createElement("div");
parentDiv.setAttribute("id","parentDiv");
parentDiv.setAttribute("id","childDiv");
子div和h2和p的制作和附加到子div从这里开始
var childDiv=document.createElement("div");
var movieElement=document.createElement("h2");
movieElement.setAttribute("id","moviename");
var yearElement=document.createElement("p");
yearElement.setAttribute("id","year");
childDiv.appendChild(movieElement);
childDiv.appendChild(yearElement);
parentDiv.appendChild(childDiv);
document.body.appendChild(parentDiv);
//document.getElementsByTagName("h2")[i].innerHTML="<b>" + title + "</b><br>";
//document.getElementsByTagName("p")[i].innerHTML= year + "<br>"; }
});
}
当第二次调用这个函数时,子div正在再次创建,虽然我已经首先声明为空(在第二行排序函数中)父div中的元素,然后从beggining创建子div。
function show(){
var z=document.getElementById("sortOrder").value;
sort(z);
//sort(Year)
//sort(title)
};
答案 0 :(得分:0)
除非它是拼写错误,否则你会覆盖父母的ID:
var parentDiv=document.createElement("div");
parentDiv.setAttribute("id","parentDiv");
parentDiv.setAttribute("id","childDiv"); // <--
答案 1 :(得分:0)
问题是父div也总是在for循环中创建,所以空删除