演示: http: //jsfiddle.net/nEh89/31/(代码如下)
<table>
<tr class='row-1'>
<td>Foo</td>
</tr>
<tr class='row-2'>
<td>Bar</td>
</tr>
<tr class='row-3'>
<td>Rab</td>
</tr>
</table>
<!-- This button will toggle all elements with css class "row-1" -->
<a class='btn hide-1' data-hide-element='row-1' data-default-mode='visible'>Toggle row with class "row-1"</a>
<!-- This button will toggle all elements with css class "row-2" -->
<a class='btn hide-2' data-hide-element='row-2' data-default-mode='hidden'>Toggle row with class "row-2"</a>
<!-- This button will toggle all elements with css class "row-3" -->
<!-- if @data-default-mode is not specified it is "visible" -->
<a class='btn hide-3' data-hide-element='row-3'>Toggle row with class "row-3"</a>
/**
* This function toggle (shows/hides) elements and
* remember visibility in browsers localStorage.
*
* @param {String} buttonsCssClass Buttons css class which will trigger toggle action.
* @return {Void}
*/
function toggleElements(buttonsCssClass) {
var // Our object of flags to determine if elements are hidden or not
elementsVisible = localStorage.getItem('elementsVisible'),
// List of buttons
btns = document.getElementsByClassName(buttonsCssClass);
// "rowHidden" not exists in localStorage yet
if (elementsVisible === null) {
elementsVisible = {};
} else {
// localStorage return string
elementsVisible = JSON.parse(elementsVisible);
}
// Bind buttons
var i = btns.length,
cls, mode, elements, x, btn;
while (i--) {
btn = btns[i];
cls = btn.getAttribute('data-hide-element');
mode = btn.getAttribute('data-default-mode');
if (typeof elementsVisible[cls] !== 'boolean') {
elementsVisible[cls] = (mode === 'visible' || mode === null) ? true : false;
}
btn.addEventListener('click', function() {
var _cls = this.getAttribute('data-hide-element');
elementsVisible[_cls] = ! elementsVisible[_cls];
localStorage.setItem('elementsVisible', JSON.stringify(elementsVisible));
toggleDisplay(_cls, elementsVisible[_cls]);
}, false);
toggleDisplay(cls, elementsVisible[cls], true);
}
function toggleDisplay(cls, visible) {
var elements = document.getElementsByClassName(cls);
x = elements.length;
while (x--) {
elements[x].style.display = visible ? '' : 'none';
}
// Change color of buttons
var btns = document.querySelectorAll('[data-hide-element="'+cls+'"]'),
i = btns.length;
while (i--) {
btns[i].style.backgroundColor = visible ? 'white' : 'red';
}
};
};
toggleElements('btn');