简体   繁体   English

刷新页面时hasClass不起作用

[英]hasClass is not working when page is refreshed

I'm trying to say if body has x class to add x class. 我想说一下body是否有x类来添加x类。

Javascript 使用Javascript

$('body').toggleClass('projectLoaded');
$('[data-type="projectLoader"]').click(function() {
  var proj = $(this)[0].getAttribute('data-project');
  $('#arrow-nav').addClass('slideIn');

  updateHash(proj);
  return false;
});
$('[data-type="projectDie"]').click(function() {

  $('body').removeClass('projectLoaded');
  $('#arrow-nav').removeClass('slideIn');
  return false;
});

if ($('body').hasClass('projectLoaded')) {
  $('#arrow-nav').addClass('slideIn');
} else {
  $('#arrow-nav').removeClass('slideIn');
}

When projectLoaded is triggered, the addClass does work for slideIn , but when I refresh, even though projectLoaded is active, the addClass disappears. 触发projectLoadedaddClass确实适用于slideIn ,但是当我刷新时,即使projectLoaded处于活动状态, addClass projectLoaded消失。 I thought a hasClass would work but it doesn't. 我以为hasClass可以工作,但是不行。 Everything works but, it's just on refresh it disappears. 一切正常,但是只要刷新,它就会消失。

Working page here , click a project and you'll #arrow-nav.slideIn working, but refresh and the .slideIn isn't added. 在这里的工作页面上,单击一个项目,您将#arrow-nav.slideIn工作,但不会刷新并添加.slideIn

UPDATE This is what worked for me: 更新这对我有用:

$( 'document' ).ready(function() {
        if ($('body').hasClass('projectLoaded')) {
            $('#arrow-nav').addClass('slideIn');
        } else {
            $('#arrow-nav').removeClass('slideIn');
        }
});

or 要么

$( 'body.projectLoaded' ).ready(function() {
    $('#arrow-nav').addClass('slideIn');
});

If this is not proper or there's a more efficient way of doing this please submit it below. 如果这样做不合适或有更有效的方法,请在下面提交。

checking ready as follows may help 如下准备检查可能会有所帮助

$( document ).ready(function() {
    console.log( "ready!" );
    $('body').toggleClass('projectLoaded');
});

My instinct tells me this will work to, but didnt test it. 我的直觉告诉我这将起作用,但没有进行测试。

$( 'body' ).ready(function() {
    console.log( "ready!" );
    $('body').toggleClass('projectLoaded');
});

$('body').toggleClass('projectLoaded') is given with in the function loadProject() which is executed after the hasClass condition is checked. $('body')。toggleClass('projectLoaded')在函数loadProject()中提供,该函数在检查hasClass条件之后执行。 So before the class 'projectLoaded' is added in the body the hasClass condition is exceuted, so the class 'slideIn' is not added. 因此,在将“ projectLoaded”类添加到主体之前,先执行hasClass条件,因此不会添加“ slideIn”类。 Try this statement '$('body').toggleClass('projectLoaded')' in the document ready just like above. 像上面一样,在文档中尝试使用此语句'$('body')。toggleClass('projectLoaded')'。 It will work. 它会工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM