【问题标题】:when this function is called second time the child divs are creating again当第二次调用此函数时,子 div 将再次创建
【发布时间】:2016-05-29 19:30:32
【问题描述】:
 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;

循环从这里开始创建 div 元素。

    for(i=0;i<Search.length;i++){
    var title=Search[i].Title;
    var year=Search[i].Year;

包含子 div 的父 div,其中存在 h2 和 p。

    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 中的元素,然后从开始创建子 div。

function show(){
var z=document.getElementById("sortOrder").value;
sort(z);
//sort(Year)
//sort(title)
};

【问题讨论】:

    标签: javascript jquery html for-loop


    【解决方案1】:

    除非是拼写错误,否则您将覆盖父 div 的 id:

    var parentDiv=document.createElement("div");
    parentDiv.setAttribute("id","parentDiv");
    parentDiv.setAttribute("id","childDiv"); // <-- 
    

    【讨论】:

      【解决方案2】:

      问题是父 div 也总是像在 for 循环中一样创建,所以空删除

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-26
        • 1970-01-01
        • 2019-05-26
        • 2019-04-20
        • 1970-01-01
        • 2015-10-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多