javascript / rails:翻开一组<a href="">s to have a class=&#34;inactive&#34;

时间:2015-07-11 11:06:31

标签: javascript jquery ruby-on-rails-4 jquery-ui-datepicker slick.js

tl;dr I would like to take an array of datetimes and using javascript (and any necessary erb tags), give all <a href>s with one of those datetimes in the url an <a class="inactive">.

This is my first question asked on SO, so please bear with me.

I have 2 javascript objects that contain a bunch of links or <a href>s to days in a calendar. One is a slick.js carousel that shows days of the week from Apr 5 to July 12. The other is a jquery ui datepicker. They both essentially contain the same set of links to localhost:3000/games?date=date where date is in the format of e.g. 20150405. Each link shows a list of baseball games being played on that date.

However, I would like to make all <a href> days with no games being played to have have the inactive class or <a class="inactive">.

This is a Rails application, but my thinking is that I need to use javascript to accomplish this correctly, but using erb tags whenever necessary.

I guess I could start creating an array in my games_controller of all dates that have 0 games? But then how would I then make all <a href>s with ?date='date_with_no_games' to have <a class="inactive">?

One other wrinkle is that the slick carousel goes by index. So in essence, start_date = ?20150405 (Apr 5th) = data-slick-index="0". For example, in order for me to determine which index initialSlide should be, I do this: data-slick='{"initialSlide": <%= (game_date.beginning_of_week - @start_date).to_i %>}'. That way, the carousel always begins on the Monday of the week of the day I'm looking at (while the day I'm on is color-coded red in that carousel). I don't know if this wrinkle will affect the answer to this question, but I wanted to include it just in case.

Okay, now for some code to give more context.

Here is the js for each of those js objects (carousel & datepicker):

// Carousel
$(document).ready(function(){
  $('.carousel-week').slick({
  });
});

// Datepicker
$.datepicker._updateDatepicker_original = $.datepicker._updateDatepicker;
  $.datepicker._updateDatepicker = function(inst) {
      $.datepicker._updateDatepicker_original(inst);
      var afterShow = this._get(inst, 'afterShow');
      if (afterShow)
          afterShow.apply((inst.input ? inst.input[0] : null));  // trigger custom callback
  }

  $( "#datepicker" ).datepicker({
    showOn: "both",
    buttonText: "<i class='fa fa-lg fa-calendar text-danger'></i>",
    afterShow :function(){
     var $dp=$("#ui-datepicker-div");

      $dp.find('.ui-state-default').each(function(){
            var $td=$(this).parents('td');
            var month=parseInt($td.attr('data-month'));                
            month++;
            var year=$td.attr('data-year')
            var day=parseInt($(this).text());
            if(month<10) month='0'+month;
            if(day<10) day='0'+day;
            var date=year+month+day;
          $(this).attr('href','<%= request.base_url + '/games' %>?date='+date);
      }).click(function(){
              window.location=$(this).attr('href');
      });     
    },
  });

Here is the erb portion of the carousel (the datepicker is one measly line and not relevant):

<div class="carousel-week col-lg-4 col-lg-offset-4 col-md-4 col-md-offset-4 col-sm-4 col-sm-offset-4 col-xs-6 col-xs-offset-3" data-slick='{"slidesToShow": 7, "slidesToScroll": 7, "initialSlide": <%= (game_date.beginning_of_week - @start_date).to_i %>}'>
    <% @schedule.each do |date| %>
      <div><%= link_to games_path(date: date.strftime("%Y%m%d")), class: (date == game_date ? "red" : "") do %>
        <%= date.strftime("%a") %> <span><%= date.strftime("%-d") %></span>
      <% end %></div>
    <% end %>
</div>

And my games_controller in case you need that as well:

class GamesController < ApplicationController

  def index
    @games = Game.where(game_date: game_date.to_date)
    distinct_dates = Game.reorder("game_date").select("game_date").distinct
    @start_date = distinct_dates.first.game_date.to_date
    end_date = distinct_dates.last.game_date.to_date
    @schedule = @start_date..end_date
  end

  def game_date
    if params[:date].present?
      date = Date.strptime(params[:date], "%Y%m%d")
    else
      date = (Time.zone.now - 9.hours).to_date
    end
  end

  helper_method :game_date

end

Thank you very much! (I'm a beginner, so sorry for the ugly code and long question!)

1 个答案:

答案 0 :(得分:0)

如果有人需要想出这样的事情,那么这对我有用:

要制作没有游戏无效的日期选择日,我在javascript中执行了

var availableDate = <%= @distinct_dates.collect { |c| c.strftime('%Y%m%d') }.to_json.html_safe %>
$.datepicker._updateDatepicker_original = $.datepicker._updateDatepicker;
  $.datepicker._updateDatepicker = function(inst) {
      $.datepicker._updateDatepicker_original(inst);
      var afterShow = this._get(inst, 'afterShow');
      if (afterShow)
          afterShow.apply((inst.input ? inst.input[0] : null));  // trigger custom callback
  }

  $( "#datepicker" ).datepicker({
    defaultDate: new Date(<%= game_date.to_time.to_i * 1000 %>),
    showOn: "both",
    buttonText: "<i class='fa fa-lg fa-calendar text-danger'></i>",
    afterShow :function(){
     var $dp=$("#ui-datepicker-div");

      $dp.find('.ui-state-default').each(function(){
            var $td=$(this).parents('td');
            var month=parseInt($td.attr('data-month'));                
            month++;
            var year=$td.attr('data-year')
            var day=parseInt($(this).text());
            if(month<10) month='0'+month;
            if(day<10) day='0'+day;
            var date=year+month+day;
            if ($.inArray(date, availableDate) >= 0){
              $(this).attr('href','<%= request.base_url + '/games' %>?date='+date);
            } else {
              $(this).removeClass('ui-state-default').addClass('ui-state-disabled');
            }
      }).click(function(){
        var href = $(this).attr('href');
        if (href == '#') {
          return false
        } else {
            window.location=href;
        }
      });     
    },
  });

然后为了使轮播日期没有游戏无效,我使用了helper_method:

module GamesHelper
  def class_for_game_link(date, dates_with_games)
    class_name = []
    class_name << 'inactive' unless dates_with_games.include?(date)
    class_name << 'red' if date == game_date
    class_name.join(' ')
  end
end

然后这是我在erb中的旋转木马:

<div class="carousel-week col-lg-4 col-lg-offset-4 col-md-4 col-md-offset-4 col-sm-4 col-sm-offset-4 col-xs-6 col-xs-offset-3" data-slick='{"slidesToShow": 7, "slidesToScroll": 7, "initialSlide": <%= (game_date.beginning_of_week - @start_date).to_i %>}'>
    <% @schedule.each do |date| %>
      <div>
        <% if @distinct_dates.include?(date) %>
          <%= link_to games_index_path(date: date.strftime("%Y%m%d")), class: class_for_game_link(date, @distinct_dates) do %>
            <%= date.strftime("%a") %> <span><%= date.strftime("%-d") %></span>
          <% end %>
        <% else %>
          <%= date.strftime("%a") %> <span><%= date.strftime("%-d") %></span>
        <% end %>
      </div>
    <% end %>
  </div>