Js日期和开关功能

时间:2016-12-02 07:46:55

标签: javascript html

html文件只包含一个id为“container”的包装器,当然还包含jQuery的google apis。

$(document).ready(function(){
for (i=1; i<=24; i++) {
    $("#container").append("<div class='divs' id='divs"    +i+     "'>"    +i+     "</div>");
} 
});
var d = new Date();
var month = d.getMonth();
var day = d.getDate();
if(month == 11){
$(document).ready(function(){
    $('.divs').each(function () {
            $(this).click(function(){

                if($(this.id == day)){
                    alert("something");
                }else{
                    alert("something else");
                }
            });
    });
 });
 }

现在这是我的代码。有没有办法让我实际检查包含数字的ID(它们都是)是否与日期相同。

2 个答案:

答案 0 :(得分:0)

创建一个包含24种不同情况的switch语句,如果在执行相同的if ... elses之后你可以做的最糟糕的事情就是一个。

相反,你应该给每个div一个id,告诉你他们应该在哪一天打开(最后你有24个div,每个都带有id&#34; 0&#34;,&#34; 1&#34;,&#34; 2&#34;,...)。

当有人点击div时,获取日期,检查它是否是12月,如果是,则检查div的id是否与当天相同。

如果您仍想使用switch语句,它们看起来像这样:

switch (day) {
    case 0: 
        // Open the first div
        break;
    case 1: 
        // Open the second div
        break;
    // ...
}

我希望你明白为什么这不是最佳解决方案

答案 1 :(得分:-2)

这可能有效:

$(document).ready(function(){
  var d = new Date();
  var month = d.getMonth();
  var day = d.getDate();

  $('[class^="divs"]').click(function () {
    if(month == 11){  
        $(this).toggleClass('image'); 
    } else {
      alert("not allowed");
    }
  });
});