我想找到一个具有data-date属性的div,如果它等于今天的日期,请更改其样式。
这就是我形成该元素的方式(我必须在JS中完成):
for (let i = 0; i < datesArray.length; i++) {
const someDate = new Date(datesArray[i]);
const date = document.createElement('div');
date.setAttribute('id', '' + new Date(datesArray[i]).getTime());
date.setAttribute('class', 'date');
date.setAttribute('data-date', new Date(datesArray[i]).toDateString());
date.innerText = '' + formatDate(someDate);
daysRowFragment.appendChild(
const formattedDate = date.innerText;
const className = formattedDate.substring(0, formattedDate.indexOf(' ')).toLowerCase() === 'sat' ||
formattedDate.substring(0, formattedDate.indexOf(' ')).toLowerCase() === 'sun' ? 'day weekend' : 'day';
$(".calendar-row").append(`
<div id="` + new Date(datesArray[i]).getDate() + '-' + i + `" data-date="` + new Date(datesArray[i]).toDateString() + `" class="` + className + `">
</div>
`);
}
daysRow.appendChild(daysRowFragment);
我已经尝试过了,但是它不起作用(日期格式不一样):
$('.date').each(function (index, dateCell) {
console.log($(dateCell).attr('data-date'));
console.log(new Date());
if ($(dateCell).attr('data-date') == new Date()) {
$(dateCell).css('background-color', 'red');
}
});
答案 0 :(得分:0)
啊,我搞砸了,只好放下:
if ($(dateCell).attr('data-date') == new Date().toDateString()) {
$(dateCell).css('background-color', 'red');
}
答案 1 :(得分:0)
在这里,我尝试为您解决问题。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(function() {
$( "[data-date='todaydate']" ).each(function(){
$(this).css('color','red');
});
});
</script>
</head>
<body>
<span id="term1" data-date='todaydate'>Lorem ipsum dolor sit amet 1</span>
<span id="term2" data-date='nottoday'>Lorem ipsum dolor sit amet 2</span>
<span id="term3" data-date='nottoday'>Lorem ipsum dolor sit amet 3</span>
<span id="term4" data-date='nottoday'>Lorem ipsum dolor sit amet 4</span>
<span id="term5" data-date='todaydate'>Lorem ipsum dolor sit amet 5</span>
<span id="term6" data-date='nottoday'>Lorem ipsum dolor sit amet 6</span>
</body>
</html>