<div class="timeRow">
<div class="timeRowCell>
<a title="1/02/2014 12:00:00 PM"> </a> </div>
<div class="timeRowCell>
<a title="1/02/2014 12:15:00 PM"> </a></div>
<div class="timeRowCell>
<a title="1/02/2014 12:30:00 PM"> </a></div>
<div class="timeRowCell>
<a title="1/02/2014 12:45:00 PM"> </a></div>
<div class="timeRowCell>
<a title="1/02/2014 01:00:00 PM"> </a></div>
.
.
.
.
.
<div class="timeRowCell>
<a title="1/02/2014 07:00:00 PM"> </a></div>
<div class="timeRowCell>
<a title="1/02/2014 07:15:00 PM"> </a></div>
<div class="timeRowCell>
<a title="1/02/2014 07:30:00 PM"> </a></div>
<div class="timeRowCell>
<a title="1/02/2014 07:45:00 PM"> </a></div>
<div class="timeRowCell>
<a title="1/02/2014 08::00 PM"> </a></div>
</div>
我可以根据当前日期和时间为四个div提供背景颜色吗?就像是01/02/2014 01:15 pm,我想改变以下四个div的背景颜色
<div class="timeRowCell>
<a title="1/02/2014 01:00:00 PM"> </a> </div>
<div class="timeRowCell>
<a title="1/02/2014 01:15:00 PM"> </a></div>
<div class="timeRowCell>
<a title="1/02/2014 01:30:00 PM"> </a></div>
<div class="timeRowCell>
<a title="1/02/2014 01:45:00 PM"> </a></div>
答案 0 :(得分:0)
我认为这应该适合你。
var anchors = document.getElementsByTagName('a'); // get All anchors
for (var i = 0; i < anchors.length; i++) {
var dateInAnchor = new Date(anchors[i].title); //anchor's title as date
if(dateInAnchor >= new Date("1/02/2014 01:00:00 PM") && dateInAnchor <= new Date("1/02/2014 01:45:00 PM")){ //when condition matches
var parentDiv = anchors[i].parentElement;
parentDiv.style.background = "yellow"; //change background of parent div
}
};
答案 1 :(得分:0)
您可以执行以下操作。如果您愿意,它只能匹配时间,时间和日期:
function doBackground() {
var elements = document.querySelectorAll('.timeRowCell a');
var now = new Date();
var currentHour = now.getHours();
var ampm = currentHour < 12? 'am' : 'pm';
// To match on time only, use this line
var re = new RegExp((currentHour%12 || 12) + ':\\d\\d:\\d\\d ' + ampm, 'i');
// To match on date also, use these lines
function z(n){return (n<10?'0':'') + n}
var re = new RegExp(now.getDate() + '\\/' + z(now.getMonth()+1) +
'\\/' + now.getFullYear() +
' ' + (currentHour%12 || 12) +
':\\d\\d:\\d\\d ' + ampm, 'i'
);
// Loop over elements looking for matches to change the background of
for (var i=0, iLen=elements.length; i<iLen; i++) {
if (re.test(elements[i].title)) {
elements[i].parentNode.style.backgroundColor = 'red';
}
}
}
它创建一个Date对象和正则表达式,并且只对与选择条件匹配的锚点进行循环,因此应该非常快。请注意,它需要支持querySelectorAll,因此IE 8及更高版本(或任何合理的现代浏览器)。