jQuery append only once

断了今生、忘了曾经 提交于 2019-12-12 09:58:24

问题


So I have this:

jQuery("document").ready(function($){

var nav = $('#nav');
var logo = '<img src="img/logo.png" />';

$(window).scroll(function () {
    if ($(this).scrollTop() > 136) {
        nav.addClass("nav-f");
        nav.append(logo);
    } else {
        nav.removeClass("nav-f");
        nav.remove(logo);
    }
});

});

When scrolling I'm trying to make the navigation to be fixed, which works, but I also want to add a tag with the logo image in the #nav div, which also works but it appends on every scroll so when scrolling I get like 100 images of the logo.

How can I make it to append only once and when it's not scrolled more than 136px to be removed?


回答1:


just use a boolean,

jQuery("document").ready(function($){

    var nav = $('#nav');
    var logo = '<img id="lilLogo" src="img/logo.png" />';
    var visible = false;

    $(window).scroll(function () {
            if ($(this).scrollTop() > 136) {
                nav.addClass("nav-f");
                if(!visible) {
                    nav.append(logo);
                    visible = true;
                }
            } else {
                nav.removeClass("nav-f");
                if(visible)  {
                    $('#lilLogo').remove();
                    visible = false;
                }
            }
        });
    });

fiddle

The alternative is to check with $('#lilLogoID').is(':visible'), however this would then do a search for img and check visible on every event (which would be slow)




回答2:


jQuery("document").ready(function($){

var nav = $('#nav');
var logo = '<img id="lilLogo" src="img/logo.png" />';    
$(window).scroll(function () {
    if ($(this).scrollTop() > 136) {
        nav.addClass("nav-f");  
        if (!$(".nav-f").find('#lilLogo').length) {
        nav.append(logo);
        }
    } else {

        nav.removeClass("nav-f");
            nav.remove(logo);

    }
});
});



回答3:


Add a class say scroll to #nav. Then inside $(window).scroll(function () { check that whether #nav .hasClass() the class scroll, if it has the do the rest or else dont..at the end of if remove the class by .removeClass()



来源:https://stackoverflow.com/questions/24206953/jquery-append-only-once

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!