隐藏已附加内容的问题

时间:2018-04-26 08:48:10

标签: jquery

当我按showAllButton时,我从数组中加载了8个配置文件; 4名女性和4名男性。

然后当我按showAllMenBtn时,我再次加载4个男性个人资料。

但是它们叠加在已经附加的内容之上。

如何制作它以替换已经添加的配置文件?

我已经尝试了很多.toogle().hide()但没有取得任何成功。

提前致谢:)

$("#showAllBtn").click(function(){

    $(allProfiles).each(function(index, profile){

        let profileImg = $("<img>", {src:`${profile.imageSrc}`});            
        let newName = profileName = profile.name;
        let newAge = profileAge = profile.age;
        let newGender = profileGender = profile.gender;
        let newInterests = profileInterests = profile.description;

        $("#profileSection").append(profileImg, newName, newAge, newGender, newInterests);


    })

});

$("#showAllMenBtn").click(function(){   


    $(maleProfiles).each(function(index, profile){

        let profileImg = $("<img>", {src:`${profile.imageSrc}`});            
        let newName = profileName = profile.name;
        let newAge = profileAge = profile.age;
        let newGender = profileGender = profile.gender;
        let newInterests = profileInterests = profile.description;


        $("#profileSection").append(profileImg, newName, newAge, newGender, newInterests);
    })

});

2 个答案:

答案 0 :(得分:4)

在第二次点击处理程序中使用.html()

$("#profileSection").html(profileImg, newName, newAge, newGender, newInterests);

注意: - .html()删除旧数据,然后在给定元素(选择器)中添加新数据

所以第二个代码必须是这样的: -

$("#showAllMenBtn").click(function(){   

    $(maleProfiles).each(function(index, profile){

        let profileImg = $("<img>", {src:`${profile.imageSrc}`});            
        let newName = profileName = profile.name;
        let newAge = profileAge = profile.age;
        let newGender = profileGender = profile.gender;
        let newInterests = profileInterests = profile.description;

        $("#profileSection").html(profileImg, newName, newAge, newGender, newInterests);
    })
});

答案 1 :(得分:1)

我认为这会奏效。

$("#showAllBtn").click(function(){

    $("#profileSection").html("");
    $(allProfiles).each(function(index, profile){

        let profileImg = $("<img>", {src:`${profile.imageSrc}`});            
        let newName = profileName = profile.name;
        let newAge = profileAge = profile.age;
        let newGender = profileGender = profile.gender;
        let newInterests = profileInterests = profile.description;

        $("#profileSection").append(profileImg, newName, newAge, newGender, newInterests);


    })

});

$("#showAllMenBtn").click(function(){   
   $("#profileSection").html("");

    $(maleProfiles).each(function(index, profile){

        let profileImg = $("<img>", {src:`${profile.imageSrc}`});            
        let newName = profileName = profile.name;
        let newAge = profileAge = profile.age;
        let newGender = profileGender = profile.gender;
        let newInterests = profileInterests = profile.description;


        $("#profileSection").append(profileImg, newName, newAge, newGender, newInterests);
    })

});