Javascript中的3周周期?

时间:2014-11-19 21:08:53

标签: javascript html web-applications web

我目前正在学习JavaScript,而我正在尝试制作一个HTML Web App,为我的学校食堂展示菜单。 我的学校有3周的菜单周期,如下:

| Week | Menu |
| 1    | 1    |
| 2    | 2    |
| 3    | 3    |
| 4    | 1    |
| 5    | 2    |
| 6    | 3    |

我不知道如何在JavaScript中执行此操作,因此完整的解释会很棒!

编辑:好的,没解释得很好;

菜单将显示为表格。我知道基本的JavaScript,但在'时间'上并不多。

解释越详细越好!

编辑2:我将有3个不同的表格,我想在3周的周期内每周显示不同的表格。对我糟糕的解释真的很抱歉。

2 个答案:

答案 0 :(得分:0)

我认为执行此类操作的最佳方法是将菜单数据存储在JSON文件或JSON对象中(在下面的示例中完成),然后在无序列表(或表)中显示菜单。

如果正确设置了客户端计算机的日期,则可以自动完成周的选择并显示正确的菜单。 (也许使用来自时间服务器或托管服务器的日期会更好。)

以下jsFiddle应该完成这项工作(它的代码与下面的代码相同)。

如果您想测试页面加载的周选择是否有效,您可以将变量startWeek修改为46,45,43,...

您需要检查的下一个也是最后一个事项是示例中没有实现的价格的数字格式,但这应该没问题。



var menues = [ { 'name': 'pasta week',
                'meals': [
                    {'name': 'noodles', 'price': 2.5},
                    {'name': 'pizza',   'price': 8.0}, 
                    {'name': 'lasagne', 'price': 5.0}]     
               },
               { 'name': 'beef week',
                 'meals': [
                    {'name': 'Club steak', 'price': 10},
                    {'name': 'Entrecote',   'price': 15}, 
                    {'name': 'Filet', 'price': 15}] 
               },
               { 'name': 'veggie week',
                'meals': [
                    {'name': 'salad', 'price': 3},
                    {'name': 'tofu burger',   'price': 4}, 
                    {'name': 'greenstuff', 'price': 3.5}]
               }
             ];

var startWeek = 47; // week of year that start with menu 1

$("select[name=week]").change(function() {
  changeMenu(this.value); //pass current selection value to function
});

function changeMenu(selection) {
  //console.log(selection);         // just for debugging
  var currentWeek = selection - 1; // -1 because array start with index 0
  var menu = menues[currentWeek]; // store menu of week in variable
  var weekName = menu.name;
  var weekMenues = menu.meals;
  var $menuTable = $("#menu"); // store jQuery object of ul list

  // set value of select box -> can be wrong if week selected from js
  $("select[name=week]").val(selection);


  $("#weekName").html(weekName); // add week name to h2 tag
  $menuTable.empty(); // clear ul to always start with an empty ul

  for (var i = 0; i < weekMenues.length; i++) {
    // loop through list and add meals to ul list
    $menuTable.append("<li class='list-group-item'>" + weekMenues[i].name + "<p class='price'>" + weekMenues[i].price + " $</li>");
  }
}

// extend date to have a getWeek method
// source from here http://zerosixthree.se/snippets/get-week-of-the-year-with-jquery/
Date.prototype.getWeek = function() {
  var onejan = new Date(this.getFullYear(), 0, 1);
  var today = new Date(this.getFullYear(), this.getMonth(), this.getDate());
  var dayOfYear = ((today - onejan + 86400000) / 86400000);
  return Math.ceil(dayOfYear / 7)
};

// the following code runs on page load to setup menu
// get current week
var today = new Date();
var currentWeek = today.getWeek();

// check which menu to choose
var menuOfWeek = ((currentWeek - startWeek) % 3) + 1;
//+1 because calculation result in 0 for cureent week and it should be 1
//console.log(menuOfWeek);

// select week on page load
changeMenu(menuOfWeek);
&#13;
body {
  padding-left: 5px;
}
#menu {
  width: 50%;
}
.price {
  float: right;
  width: 20%;
  color: gray;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">

<h1>Menu of the week</h1>
<h2 id="weekName"></h2>
<ul id='menu' class="list-group">
</ul>

<b>Choose your week:</b>
<select name="week" size="1">
  <option>1</option>
  <option>2</option>
  <option>3</option>
</select>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

另一种方法是使用AngularJS。但也许这有点先进。无论如何,这里的好处是你不必做任何DOM操作。 这是Angular的双向数据绑定的工作。

我做了两个带有指令的版本1和带有控制器的版本。带控制器的那个更容易理解。但我更喜欢指令方法。这就是我在这里发布的原因。

控制器变体也可以使用,可以在this jsFiddle中找到。

AngularJS的另一个好处是过滤器{{menu.price | currency}}。这就是货币过滤器正确显示价格的原因(例如$ 3.50)。无需额外编程。

(如果你更喜欢jsFiddle,这里是指令方法的链接,版本如下:Directive Menu angularJS

代码行与jQuery版本的代码行非常相似(如果您将Angular指令的HTML模板移动到单独的文件中)。

&#13;
&#13;
"use strict";

var app = angular.module('MenuApp', []);

// possible improvements:
// - menues data in separate JSON file
// - menu template in separate HTML template file 
//   (use templateURL instead of template)

app.directive('menu', function(){  
    return {
        scope: true,
        controller: function($scope) {
            // Initialization
            var menues = [{ 'name': 'pasta week',
                            'meals': [
                            {'name': 'noodles', 'price': 2.5},
                            {'name': 'pizza',   'price': 8.0}, 
                            {'name': 'lasagne', 'price': 5.0}]     
                          },
                          { 'name': 'beef week',
                            'meals': [
                            {'name': 'Club steak', 'price': 10},
                            {'name': 'Entrecote',   'price': 15}, 
                            {'name': 'Filet', 'price': 15}] 
                          },
                          { 'name': 'veggie week',
                            'meals': [
                            {'name': 'salad', 'price': 3},
                            {'name': 'tofu burger',   'price': 4}, 
                            {'name': 'greenstuff', 'price': 3.5}]
                          }
                        ];

            var startWeek = 47; // week of year that start with menu 1
            
            // Event handlers
            var that = this;
            
            $scope.onWeekChange = function () {
                that.changeMenu($scope.selectedWeek);
            };
            
            this.changeMenu = function(selection) {
                var currentWeek = selection-1;  // -1 because array start with index 0
                var menu = menues[currentWeek]; // store menu of week in variable
                $scope.weekMenue = menu;
            }
            
            // getWeek (modified)
            // source from here http://zerosixthree.se/snippets/get-week-of-the-year-with-jquery/
            var getWeek = function() {
                var curdate = new Date();
                var onejan = new Date(curdate.getFullYear(),0,1);
                var today = new Date(curdate.getFullYear(),curdate.getMonth(),curdate.getDate());
                var dayOfYear = ((today - onejan + 86400000)/86400000);
                return Math.ceil(dayOfYear/7);
            };

            var setCurrentWeek = function() {
                var currentWeek = getWeek();
                var menuOfWeek = ( ( currentWeek - startWeek ) % 3 ) + 1; 
                //+1 because calculation result in 0 for cureent week and it should be 1
                return menuOfWeek;
            };
            
            this.init = function() { 
                $scope.selectedWeek = setCurrentWeek();
                this.changeMenu($scope.selectedWeek);
            };
            
            this.init();                    
        },
        template:
            '<h2 id="weekName">{{weekMenue.name}}</h2>' +
            '<ul id="menu" class="list-group">' +
            '   <li class="list-group-item" ng-repeat="menu in weekMenue.meals">'  +
            '   {{menu.name}}<span class="price">{{menu.price | currency}}</span>' +
            '   </li>' +
            '</ul>'+  
            '<b>Choose your week:</b>' +
            '<select name="week" size="1" ng-model="selectedWeek" ng-change="onWeekChange()">' +
            '   <option>1</option>' +
            '   <option>2</option>' +
            '   <option>3</option>' +
            '</select>'
    };
});
&#13;
body {
    padding-left: 5px;
}
#menu {
    width: 50%;
}
.price{
    float:right;
    color: gray;
}
&#13;
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/>


<div ng-app="MenuApp">
    <h1>Menu of the week</h1>
    <menu></menu>
</div>
&#13;
&#13;
&#13;