如何根据当前事件日期突出显示元素?

时间:2012-12-19 18:24:30

标签: javascript jquery html

我从SO上提出的另一个问题中借用了一些代码,因为我找不到一个可以实现我想要实现的脚本。

我想要做的是根据分配的日期突出显示当前事件,以下代码不适用于表格内的<td>元素,<div>或一个<p>元素。

我还想将重点应用于同名的任何ID,这可能与我现在拥有的一样吗?

<!DOCTYPE html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title></title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.2.js'></script>
<style>
body {padding: 20px; font-family: sans-serif;}
p {margin-top: 80px; font-size: 11px;}
.active {color: hotpink;
background:#000;
font-weight:bold;
}
</style>
<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
var TODAY = new Date();
//Individual dates could be organized as objects, but using arrays below seems to be more readable and tidy
var SCHEDULE = {
'some-class': ['May 5 2011', 'June 5 2011'],
'some-class-a': ['May 5 2012', 'June 5 2012'],
'some-class-b': ['May 10 2012', 'June 10 2012'],
'some-class-c': ['December 15 2012', 'December 31 2012'],
'some-class-d': ['May 20 2012', 'June 20 2012'],
'some-class-e': ['December 15 2012', 'December 31 2012']
};
for (var events_ in SCHEDULE) {
console.log('checking ' + events_ + ', dates have to be within the ' + SCHEDULE[events_] + ' range');
if (TODAY >= Date.parse(SCHEDULE[events_][0]) && TODAY <= Date.parse(SCHEDULE[events_][1])) {
console.log(events_ + ' is currently in session!');
document.getElementById(events_).classList.add('active');
}
}
});//]]>
</script>
</head>
<body>
<ul>
<li id="some-class">Event 1</li>
<li id="some-class-a">Event 2</li>
<li id="some-class-b">Event 3</li>
<li id="some-class-c">Event 4</li>
<li id="some-class-d">Event 5</li>
<li id="some-class-e">Event 6</li>
</ul>
<p id="some-class-e">Current event here text</p>
<div id="some-class-e">Current event here, more text</div>
<table id="events" border="1">
<tr>
<td>Event 1 (May 16 - Dec 1)</td>
</tr>         
<tr>
<td>Event 2 (May 31 - June 1)</td>
</tr>
<tr>
<td id="some-class-e">Current Event (December 15 - December 31)</td>
</tr>               
</table>
</body>
</html>

jsFiddle demo

1 个答案:

答案 0 :(得分:7)

首先,ID必须是唯一的,并且通过使用document.getElementById,您只会获取一个。{/ p>

如果您想多次使用相同的标识符(例如,some-class-e),则需要使用类名。

您可以使用document.getElementsByClassName按类名获取所有元素,然后将active类名应用于它。

<ul><li class="some-class-e">Event 6</li></ul>
<p class="some-class-e">Current event here text</p>
<div class="some-class-e">Current event here, more text</div>

var matches = document.getElementsByClassName(events_);
for(var i = 0; i < matches.length; ++i){
  matches[i].classList.add('active');
}

See it here.


更新

jQuery变体:

$.each(SCHEDULE, function(classname, dates) {
  if (TODAY >= Date.parse(dates[0]) && TODAY <= Date.parse(dates[1])) {
    $("." + classname).addClass("active");
  }
});

There you go.