我会在这个答案中向您建议一些最佳实践:
- 使用类而不是样式属性,这对浏览器来说更好。
- 不要使用内联事件处理程序。请参见下面的示例。
- 您正在寻找的不是“替换”,而是“切换”。
- 我建议你使用事件冒泡。这样,您就可以在所有 div 的容器上添加一个事件,然后就可以处理它了。
好的,现在举个例子:
HTML:
<div id="container">
<div id="div1">..</div>
<div id="div2" class="hidden">..</div>
<div id="div3" class="hidden">..</div>
</div>
JS:
// Notice how I declare an onclick event in the javascript code
document.getElementById( 'container' ).onclick = function( e ) {
// First, get the clicked element
// We have to add these lines because IE is bad.
// If you don't work with legacy browsers, the following is enough:
// var target = e.target;
var evt = e || window.event,
target = evt.target || evt.srcElement;
// Then, check if the target is what we want clicked
// For example, we don't want to bother about inner tags
// of the "div1, div2" etc.
if ( target.id.substr( 0, 3 ) === 'div' ) {
// Hide the clicked element
target.className = 'hidden';
// Now you have two ways to do what you want:
// - Either you don't care about browser compatibility and you use
// nextElementSibling to show the next element
// - Or you care, so to work around this, you can "guess" the next
// element's id, since it remains consistent
// Here are the two ways:
// First way
target.nextElementSibling.className = '';
// Second way
// Strip off the number of the id (starting at index 3)
var nextElementId = 'div' + target.id.substr( 3 );
document.getElementById( nextElementId ).className = '';
}
};
当然,CSS:
.hidden {
display: none;
}
我强烈建议您阅读 javascript 代码中的注释。
如果你仔细阅读,你会发现在现代浏览器中,JS 代码只有 5 行。不再。要支持旧版浏览器,它需要 7 行代码。