targeting unique and first duplicate members of an array
I have a 6 divs in a html doc that have the following characteristics:
<div id="m1_1" title="Sept. 05, 2011" class="eheader">MR 1 —</div>
<div id="m1_8" title="Sept. 05, 2011" class="eheader">MR 8 —</div>
<div id="m1_12" title="Sept. 05, 2011" class="eheader">MR 12 —</div>
<div id="m1_16" title="Sept. 12, 2011" class="eheader">MR 16 —</div>
<div id="m1_17" title="Sept. 12, 2011" class="eheader">MR 17 —</div>
<div id="m1_19" title="Sept. 15, 2011" class="eheader">MR 19 —</div>
Their id's are something like m1_1, m1_2, m1_3, m1_4, m1_5 and m1_6. The numerical digits after the underscore are generated dynamically so I can't directly target say… "m1_8".
They all share the same class which is unique to the group. In my css I'm setting the display property for divs of this class to "hidden" or "none".
They all have a title element which is set to the date they were created.
What I need is a function that will loop through the divs by class name and target all of the unique titles and the first member of any duplicate titles. In the above example, m1_19 would be targeted because its title (create date) is unique to the set. divs m1_1 and m1_16 would also be targeted because they are the first members of duplicates.
My function outline looks like this… of course there's a huge chunk of logic missing and I'm not e开发者_运维技巧ven sure I set up the loop correctly. Can this be done or am I on the wrong track completely?
function checkHeaders(){
var hdrSet = document.getElementsByClassName("eheader");
for (var i=0; i<hdrSet.length; i++){
if (hdrSet[i].title {
hdrSet[i].style.display = "block";
}
}
}
function checkHeaders(){
var hdrSet = document.getElementsByClassName("eheader");
var titles = {};
for (var i=0; i<hdrSet.length; i++){
if ( !titles[ hdrSet[i].title ] ) {
titles[ hdrSet[i].title ] = true;
hdrSet[i].style.display = "block";
}
}
}
I think this is what you are after:
function checkHeaders(){
var hdrSet = document.getElementsByClassName("eheader");
var title;
for(var i=0; i<hdrSet.length; i++){
if(title != hdrSet[i].title){
title = hdrSet[i].title;
hdrSet[i].style.display = 'block';
}
}
}
checkHeaders();
Example: http://jsfiddle.net/Vk7Ud/
Explanation
var hdrSet = document.getElementsByClassName("eheader");
//grab all the divs
var title;
//set a variable to contain the titles
for(var i=0; i<hdrSet.length; i++){
//for each div
if(title != hdrSet[i].title){
//if the title does not match the one that is set, continue
//(first one is always fine, as nothing is set)
title = hdrSet[i].title;
//then set the latest title to title
hdrSet[i].style.display = 'block';
//display the div
}
}
}
checkHeaders();
function checkHeaders(){
var hdrSet = document.getElementsByClassName("eheader");
var prevTitle = '';
for (var i=0; i<hdrSet.length; i++){
if ( hdrSet[i].title) {
if ($prevTitle != hdrSet[i].title) {
hdrSet[i].style.display = "block";
}
$prevTitle = hdrSet[i].title;
}
}
}
精彩评论