4

我从另一个关于 SO 的问题中借用了一些代码,因为我找不到可以完成我想要实现的目标的脚本。

我想做的是根据分配的日期突出显示当前事件,并且以下代码不适用于<td>table、a<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 演示

4

1 回答 1

7

首先,IDs 需要是唯一的,并且通过使用document.getElementById你只会获取一个。

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');
}

看这里。


更新

一个 jQuery 变体:

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

你去吧。

于 2012-12-19T18:37:42.817 回答