最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Javascript not working on one page when it works on other page - Stack Overflow

programmeradmin4浏览0评论

Everything was working fine on home page: /, especially the stores section and the opening hours in the footer at the bottom. However, when I went to the /, the stores were not loading. It means that the javascript for this stores are not loading. But when I checked the console log, it shows that the javascript file are there and I found out that when I take out the other javascript file (the opening hours.js), it loads fine but when I put it back, the stores doesn't load. I don't understand why both files were working fine on the home page but no so on the stores page. How do I fix it? I even bined two files together and it loads fine on the home page but not so on the store page. Additionally, the stores section has mixitup plugin with jquery.mixitup.min.js.

Stores files jquery-custom-scripts.js

 ( function( $ ) {

$( document ).ready(function() {


 var dropdownFilter = {

  // Declare any variables we will need as properties of the object

  $filters: null,
  $reset: null,
  groups: [],
  outputArray: [],
  outputString: '',

  // The "init" method will run on document ready and cache any jQuery objects we will need.

  init: function(){
    var self = this; // As a best practice, in each method we will asign "this" to the variable "self" so that it remains scope-agnostic. We will use it to refer to the parent "dropdownFilter" object so that we can share methods and properties between all parts of the object.

    self.$filters = $('#Filters');
    self.$reset = $('#Reset');
    self.$container = $('#isotope-list');

    self.$filters.find('fieldset').each(function(){
      var $this = $(this);

      self.groups.push({
        $buttons : $this.find('.filter'),
                $inputsSelect : $this.find('select'),
                $inputsText : $this.find('input[type="text"]'),
                active : ''
            });
        });

    self.bindHandlers();
  },


  // The "bindHandlers" method will listen for whenever a select is changed. 

  bindHandlers: function(){
    var self = this;

    // Handle select change

 self.$filters.on('click', '.filter', function(e){
      e.preventDefault();

      var $button = $(this);

      // If the button is active, remove the active class, else make active and deactivate others.

      $button.hasClass('active2') ?
        $button.removeClass('active2') :
        $button.addClass('active2').siblings('.filter').removeClass('active2');

      self.parseFilters();
    });

    // Handle dropdown change

    self.$filters.on('change', function(){
      self.parseFilters();           
    });

     // Handle key up on inputs
        self.$filters.on('keyup', 'input[type="text"]', function() {

            var $input = $(this);
            console.log($input.val());            
            $input.attr('data-filter', '[class*="'+$input.val().replace(/ /, '-')+'"]');
            if ($input.val() == '')
              $input.attr('data-filter', '');
            console.log($input.attr('data-filter'));
            self.parseFilters();

        });

    // Handle reset click

    self.$reset.on('click', function(e){
      e.preventDefault();

      self.$filters.find('.filter').removeClass('active2');
      self.$filters.find('.show-all').addClass('active2');
      self.$filters.find('select').val('');

self.$filters.find('input[type="text"]').val('').attr('data-filter', '');

      self.parseFilters();
    });
  },

  // The parseFilters method pulls the value of each active select option

  parseFilters: function(){
    var self = this;

    // loop through each filter group and grap the value from each one.

    for(var i = 0, group; group = self.groups[i]; i++){

          var activeButtons = group.$buttons.length ? group.$buttons.filter('.active2').attr('data-filter') || '' : '';            
          var activeSelect = group.$inputsSelect.length ? group.$inputsSelect.val()  || '' : '';
          var activeText = group.$inputsText.length ? group.$inputsText.attr('data-filter') : ''; 

          group.active = activeButtons+activeSelect+activeText;

          console.log(group.active);
        } 

        self.concatenate();

    },

  // The "concatenate" method will crawl through each group, concatenating filters as desired:

  concatenate: function(){
    var self = this;

    self.outputString = ''; // Reset output string

    for(var i = 0, group; group = self.groups[i]; i++){
      self.outputString += group.active;
    }

    // If the output string is empty, show all rather than none:

    !self.outputString.length && (self.outputString = 'all'); 

    console.log(self.outputString); 

    // ^ we can check the console here to take a look at the filter string that is produced

    // Send the output string to MixItUp via the 'filter' method:

      if(self.$container.mixItUp('isLoaded')){
        self.$container.mixItUp('filter', self.outputString);
      }
  }
};

// On document ready, initialise our code.

$(function(){

  // Initialize dropdownFilter code

  dropdownFilter.init();

  // Instantiate MixItUp

  $('#isotope-list').mixItUp({
    controls: {
      enable: false // we won't be needing these
    },
    callbacks: {
      onMixFail: function(){
        alert('No items were found matching the selected filters.');
      }
    }
  });    
});

$('.btn-clear').on('click', function(event) {
    event.preventDefault();
    $(this).prev().val("").change();
  });
$('select').change(function() {
    if ($(this).val() == "") { 
        $(this).next().hide('.btn-hide');
    } else { 
        $(this).next().show('.btn-hide');
    } 
});

});

} )( jQuery );

Opening hours js file

 ( function( $ ) {

$( document ).ready(function() {

var currentDate = new Date();
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Weekday";
weekday[2] = "Weekday";
weekday[3] = "Weekday";
weekday[4] = "Weekday";
weekday[5] = "Weekday";
weekday[6] = "Saturday";

var currentDay = weekday[currentDate.getDay()];


var currentDayID = "#" + currentDay; //gets todays weekday and turns it into id
$(currentDayID).toggleClass("today"); //this works at hightlighting today


});

$( document ).ready(function() {
var dayOfWeek = (new Date).getDay();
var hours = ["Today: 9:00am to 6:00pm",          // Sunday
             "Today: 8:00am to 9:00pm",   // Monday
             "Today: 8:00am to 9:00pm",   // Tuesday
             "Today: 8:00am to 9:00pm",   // Wednesday
             "Today: 8:00am to 9:00pm",   // Thursday
             "Today: 8:00am to 9:00pm",   // Friday
             "Today: 8:00am to 5:00pm"];  // Saturday
var todaysHours = hours[dayOfWeek];
document.getElementById("hours").innerHTML = todaysHours;

});


} )( jQuery );

Everything was working fine on home page: http://kikidesign/dev/mcdowell/, especially the stores section and the opening hours in the footer at the bottom. However, when I went to the http://kikidesign/dev/mcdowell/stores/, the stores were not loading. It means that the javascript for this stores are not loading. But when I checked the console log, it shows that the javascript file are there and I found out that when I take out the other javascript file (the opening hours.js), it loads fine but when I put it back, the stores doesn't load. I don't understand why both files were working fine on the home page but no so on the stores page. How do I fix it? I even bined two files together and it loads fine on the home page but not so on the store page. Additionally, the stores section has mixitup plugin with jquery.mixitup.min.js.

Stores files jquery-custom-scripts.js

 ( function( $ ) {

$( document ).ready(function() {


 var dropdownFilter = {

  // Declare any variables we will need as properties of the object

  $filters: null,
  $reset: null,
  groups: [],
  outputArray: [],
  outputString: '',

  // The "init" method will run on document ready and cache any jQuery objects we will need.

  init: function(){
    var self = this; // As a best practice, in each method we will asign "this" to the variable "self" so that it remains scope-agnostic. We will use it to refer to the parent "dropdownFilter" object so that we can share methods and properties between all parts of the object.

    self.$filters = $('#Filters');
    self.$reset = $('#Reset');
    self.$container = $('#isotope-list');

    self.$filters.find('fieldset').each(function(){
      var $this = $(this);

      self.groups.push({
        $buttons : $this.find('.filter'),
                $inputsSelect : $this.find('select'),
                $inputsText : $this.find('input[type="text"]'),
                active : ''
            });
        });

    self.bindHandlers();
  },


  // The "bindHandlers" method will listen for whenever a select is changed. 

  bindHandlers: function(){
    var self = this;

    // Handle select change

 self.$filters.on('click', '.filter', function(e){
      e.preventDefault();

      var $button = $(this);

      // If the button is active, remove the active class, else make active and deactivate others.

      $button.hasClass('active2') ?
        $button.removeClass('active2') :
        $button.addClass('active2').siblings('.filter').removeClass('active2');

      self.parseFilters();
    });

    // Handle dropdown change

    self.$filters.on('change', function(){
      self.parseFilters();           
    });

     // Handle key up on inputs
        self.$filters.on('keyup', 'input[type="text"]', function() {

            var $input = $(this);
            console.log($input.val());            
            $input.attr('data-filter', '[class*="'+$input.val().replace(/ /, '-')+'"]');
            if ($input.val() == '')
              $input.attr('data-filter', '');
            console.log($input.attr('data-filter'));
            self.parseFilters();

        });

    // Handle reset click

    self.$reset.on('click', function(e){
      e.preventDefault();

      self.$filters.find('.filter').removeClass('active2');
      self.$filters.find('.show-all').addClass('active2');
      self.$filters.find('select').val('');

self.$filters.find('input[type="text"]').val('').attr('data-filter', '');

      self.parseFilters();
    });
  },

  // The parseFilters method pulls the value of each active select option

  parseFilters: function(){
    var self = this;

    // loop through each filter group and grap the value from each one.

    for(var i = 0, group; group = self.groups[i]; i++){

          var activeButtons = group.$buttons.length ? group.$buttons.filter('.active2').attr('data-filter') || '' : '';            
          var activeSelect = group.$inputsSelect.length ? group.$inputsSelect.val()  || '' : '';
          var activeText = group.$inputsText.length ? group.$inputsText.attr('data-filter') : ''; 

          group.active = activeButtons+activeSelect+activeText;

          console.log(group.active);
        } 

        self.concatenate();

    },

  // The "concatenate" method will crawl through each group, concatenating filters as desired:

  concatenate: function(){
    var self = this;

    self.outputString = ''; // Reset output string

    for(var i = 0, group; group = self.groups[i]; i++){
      self.outputString += group.active;
    }

    // If the output string is empty, show all rather than none:

    !self.outputString.length && (self.outputString = 'all'); 

    console.log(self.outputString); 

    // ^ we can check the console here to take a look at the filter string that is produced

    // Send the output string to MixItUp via the 'filter' method:

      if(self.$container.mixItUp('isLoaded')){
        self.$container.mixItUp('filter', self.outputString);
      }
  }
};

// On document ready, initialise our code.

$(function(){

  // Initialize dropdownFilter code

  dropdownFilter.init();

  // Instantiate MixItUp

  $('#isotope-list').mixItUp({
    controls: {
      enable: false // we won't be needing these
    },
    callbacks: {
      onMixFail: function(){
        alert('No items were found matching the selected filters.');
      }
    }
  });    
});

$('.btn-clear').on('click', function(event) {
    event.preventDefault();
    $(this).prev().val("").change();
  });
$('select').change(function() {
    if ($(this).val() == "") { 
        $(this).next().hide('.btn-hide');
    } else { 
        $(this).next().show('.btn-hide');
    } 
});

});

} )( jQuery );

Opening hours js file

 ( function( $ ) {

$( document ).ready(function() {

var currentDate = new Date();
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Weekday";
weekday[2] = "Weekday";
weekday[3] = "Weekday";
weekday[4] = "Weekday";
weekday[5] = "Weekday";
weekday[6] = "Saturday";

var currentDay = weekday[currentDate.getDay()];


var currentDayID = "#" + currentDay; //gets todays weekday and turns it into id
$(currentDayID).toggleClass("today"); //this works at hightlighting today


});

$( document ).ready(function() {
var dayOfWeek = (new Date).getDay();
var hours = ["Today: 9:00am to 6:00pm",          // Sunday
             "Today: 8:00am to 9:00pm",   // Monday
             "Today: 8:00am to 9:00pm",   // Tuesday
             "Today: 8:00am to 9:00pm",   // Wednesday
             "Today: 8:00am to 9:00pm",   // Thursday
             "Today: 8:00am to 9:00pm",   // Friday
             "Today: 8:00am to 5:00pm"];  // Saturday
var todaysHours = hours[dayOfWeek];
document.getElementById("hours").innerHTML = todaysHours;

});


} )( jQuery );
Share Improve this question asked Feb 22, 2016 at 19:38 Kristina BresslerKristina Bressler 1,7322 gold badges30 silver badges68 bronze badges 1
  • 1 Have you looked at the console? Uncaught TypeError: Cannot set property 'innerHTML' of null which is document.getElementById("hours").innerHTML = todaysHours; – ak_ Commented Feb 22, 2016 at 19:40
Add a ment  | 

2 Answers 2

Reset to default 2

Console is giving you the error of your code:

Uncaught TypeError: Cannot set property 'innerHTML' of null

As you're trying to do at line 212:

document.getElementById("hours").innerHTML = todaysHours;

Are you sure that #hours element exist? I can't find it in your HTML, so you're trying to do something with an element that doesn't exist.

You should do in order to avoid that problem:

  var DOMhours = document.getElementById("hours")
  if (DOMhours) DOMhours.innerHTML = todaysHours

If you want to do that after the stores are loaded, you should be sure that the stores are loaded and, after the stores are loaded and you've appended them to the HTML, get the #hours element and put the innerHTML that you want. But always is a good idea to check before if the element is there to avoid those errors. :)

You are trying to set the property of a DOM element that doesn't exist.

Line 212: document.getElementById("hours").innerHTML = todaysHours;

You can check the browser's console for errors like these by pressing F12.

发布评论

评论列表(0)

  1. 暂无评论