设置同一类

时间:2016-08-08 19:35:07

标签: javascript jquery

我没有。特定阶级的div。我将这些div分配给一个数组,并希望根据数组的索引设置每个div的html - 任何人都可以帮我处理代码。我尝试的代码如下:

<div class="days"></div>
<div class="days"></div>
<div class="days"></div>
<div class="days"></div>
<div class="days"></div>
<div class="days"></div>
<div class="days"></div>

arrayofDays = $('.days');

var FirstDay = 1;
var LastDay = 5;

$(arrayofDays).each(function(i, item) {
        if ((i >= FirstDay) && (i <= LastDay)) {
            $(item[i]).css({'background-color' : '#991'}).html('Weekday');
        }

        else {
            $(item[i]).css({'background-color' : '#fff'}).html('Holiday');
        } 
    });

我试图将第一个和最后一个div的html设置为'Holiday',将其他div设置为'Weekday'。到目前为止还没有取得任何进展......

提前致谢

Sukalyan

2 个答案:

答案 0 :(得分:0)

您可以使用jQuery选择器

var weekend = $('.days:first, .days:last');
var weekday = $('.days').not(weekend);

var FirstDay = 1;
var LastDay = 5;

var weekday = $('.days').slice(FirstDay, LastDay + 1);
var weekend = $('.days').not(weekday);

var weekend = $('.days:first, .days:last');
var weekday = $('.days').not(weekend);

weekday.css({'background-color' : '#991'}).html('Weekday');
weekend.css({'background-color' : '#fff'}).html('Holiday');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="days">sunday</div>
<div class="days">monday</div>
<div class="days">tuesday</div>
<div class="days">wednesday</div>
<div class="days">thursday</div>
<div class="days">friday</div>
<div class="days">saturday</div>

答案 1 :(得分:0)

使用$(item)作为选择器,jQuery.each中的第二个参数是元素本身!

&#13;
&#13;
var arrayofDays = $('.days');
var FirstDay = 1;
var LastDay = 5;
$(arrayofDays).each(function(i, item) {
  if ((i >= FirstDay) && (i <= LastDay)) {
    $(item).css({
      'background-color': '#991'
    }).html('Weekday');
  } else {
    $(item).css({
      'background-color': '#fff'
    }).html('Holiday');
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="days"></div>
<div class="days"></div>
<div class="days"></div>
<div class="days"></div>
<div class="days"></div>
<div class="days"></div>
<div class="days"></div>
&#13;
&#13;
&#13;

使用index

&#13;
&#13;
var arrayofDays = $('.days');
var FirstDay = 1;
var LastDay = 5;
$(arrayofDays).each(function(i, item) {
  if ((i >= FirstDay) && (i <= LastDay)) {
    $(arrayofDays[i]).css({
      'background-color': '#991'
    }).html('Weekday');
  } else {
    $(arrayofDays[i]).css({
      'background-color': '#fff'
    }).html('Holiday');
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="days"></div>
<div class="days"></div>
<div class="days"></div>
<div class="days"></div>
<div class="days"></div>
<div class="days"></div>
<div class="days"></div>
&#13;
&#13;
&#13;