質問

I have two separate html files being dynamically added to the index.html by means of jquery .load(). After the html content has fully loaded the fade-in animation happens. I want to call yet another function -- orientationLoad() -- depending on which html was loaded. But for what I understand the orientationLoad() is being called before the load() has completed loading. I get this console error:

TypeError: 'undefined' is not an object (evaluating '$('.page').classList.contains')

Can someone help? Thanks

function orientationLoad() {
  var viewportWidth = window.innerWidth;
  if (viewportWidth > 768) {
      landscapeClass();
  } else {
      portraitClass();
  }
};

function changePage(fileName){
    $('.content_wrapper').animate({opacity:0}, 500, function(){
        if (fileName == 'home.html?v=1'){
            $('.page').addClass('home');
        }else{
            $('.page').removeClass('home');
        }
        if (fileName == 'story.html?v=1'){
            $('.page').addClass('story');
        }else{
            $('.page').removeClass('story');
        }
    });
  // load html with jQuery's built-in Ajax instruction
  $('.content_loading_container').load('content/'+fileName, function(){
    $('.content_wrapper').delay(250).animate({opacity:1}, 500);
  });
  // if page is 'story' call orientationLoad()
  if ($('.page').classList.contains('story'))
    {
      orientationLoad();
    } else{}
};

$(document).ready(function(){
  $('nav a').on('touchstart', function(){
    changePage($(this).attr('data-file'));
  });
});
役に立ちましたか?

解決

jQuery objects do not have a classList property. To use classList, you must extract the element from the jquery object.

$('.page').get(0).classList.contains('story')

however, you can simplify this by using jquery's .is method or .hasClass method.

$('.page').is('.story'); // true/false
$('.page').hasClass('story'); // true/false

or even:

$(".page.story").length; // 0/n

Additionally, if you wanted the result of this conditional to happen after the .load has completed, you must move it inside the .load callback after your animation line.

$('.content_loading_container').load('content/'+fileName, function(){
    $('.content_wrapper').delay(250).animate({opacity:1}, 500);
    if ($('.page').hasClass('story')) {
        ...
});
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top