我需要使用moment.js根据日期更改输入字段的背景和颜色,但下面有一些代码,但它会找到日期值,然后不更改颜色。我不知道为什么没有。我会接受javascript或jquery中的任何好的答案。
var cccr_mems = [
{ "Name": "Ahmed, Jamshed", "cccrEXP": "2018.10.10" },
{ "Name": "Attaya, James J", "cccrEXP": "2019.01.12" },
{ "Name": "Badamo, Anthony", "cccrEXP": "2018.09.12" }]
function getExpireDate(ele) {
var i = null;
for (i = 0; cccr_mems.length > i; i++) {
if (cccr_mems[i].Name == ele.value) {
var exDate = moment(cccr_mems[i].cccrEXP, 'YYYY.MM.DD');
// everything works except for this next "if" statement:
// I would rather reference the input date field by ID such as id = "CCCR_X1"
if (moment().isAfter(exDate)) {
$(ele).closest('.universal').find('.CCCRexpDate').css('color', "#A3005B");
} else {
$(ele).closest('.universal').find('.CCCRexpDate').css('color', "#275052");
}
// down to here.
return cccr_mems[i].cccrEXP;
}
}
return '';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.js"></script>
<input type = "text" onblur="getExpireDate();" class="CCCRexpDate" name = "cccr_exp" id = "CCCR_X1" />
<input type = "text" onblur="getExpireDate();" class="CCCRexpDate" name = "cccr_exp" id = "CCCR_X2" />
<input type = "text" onblur="getExpireDate();" class="CCCRexpDate" name = "cccr_exp" id = "CCCR_X3" />
答案 0 :(得分:2)
这可能会有所帮助 getExpireDate中元素的第一遍引用
<input type = "text" onblur="getExpireDate(this);" class="CCCRexpDate" name = "cccr_exp" id = "CCCR_X1" />
<input type = "text" onblur="getExpireDate(this);" class="CCCRexpDate" name = "cccr_exp" id = "CCCR_X2" />
<input type = "text" onblur="getExpireDate(this);" class="CCCRexpDate" name = "cccr_exp" id = "CCCR_X3" />
然后更新getExpireDate
function getExpireDate(ele) {
var i = null;
for (i = 0; cccr_mems.length > i; i++) {
if (cccr_mems[i].Name == ele.value) {
var exDate = moment(cccr_mems[i].cccrEXP, 'YYYY.MM.DD');
if (moment().isAfter(exDate)) {
//$(ele).css('color', "#A3005B");
$(ele).css('background', "#A3005B");
} else {
$(ele).css('background', "#275052");
//$(ele).css('color', "#275052");
}
return cccr_mems[i].cccrEXP;
}
}
return '';
}
答案 1 :(得分:0)
<input type = "text" onblur="getExpireDate(this);" class="CCCRexpDate" name = "cccr_exp" id = "CCCR_X1" />
和JavaScript部分:
document.getElementById(ele.id).style.backgroundColor="#275052"