我想设置一个功能,比如点击一个链接可以显示一个p。当点击另一个链接时,之前的显示的p自动隐藏,新的p显示出来。我应该如何实现?
我的代码如下:
HTML
<a href="javascript:unhide('text1');">Text 1</a>
<a href="javascript:unhide('text2');">Text 2</a>
<a href="javascript:unhide('text3');">Text 3</a>
<p id="text1" class="unhidden">
This will show up when the Text 1 link is pressed.
</p>
<p id="text2" class="hidden">
This will show up when the Text 2 link is pressed.
</p>
<p id="text3" class="hidden">
This will show up when the Text 3 link is pressed.
</p>
Javascript
function unhide(pID) {
var item = document.getElementById(pID);
if (item) {
item.className='unhidden';
}
}
CSS
.hidden { display: none; }
.unhidden { display: block; }
原问题: Show one p and hide the previous showing p
ringa_lee2017-04-10 13:13:11
答案:
hsz:Try it
function unhide(pID) {
var unhidden = document.getElementsByClassName('unhidden');
for (var k in unhidden) {
unhidden[k].className='hidden';
}
var item = document.getElementById(pID);
if (item) {
item.className='unhidden';
}
}
OlivierH:实现方法如下
function unhide(pID) {
var ps = document.getElementsByTagName('p');
foreach(var p in ps){
p.className = 'hidden';
if(p.id == pID)
p.className = 'unhidden';
}
}
但需要注意 document.getElementsByTagName('p'); 它将返回你文档里的所有p,你可以选择给它封装起来。例如:
HTML
<p id="wrapper">
<p id="text1" class="unhidden">
This will show up when the Text 1 link is pressed.
</p>
<p id="text2" class="hidden">
This will show up when the Text 2 link is pressed.
</p>
<p id="text3" class="hidden">
This will show up when the Text 3 link is pressed.
</p>
</p>
JS
var ps = document.getElementById('wrapper').getElementsByTagName('p');
Andrew:下面这中方法也适用,DEMO:http://jsfiddle.net/L79H7/1/
function unhide(pID) {
var pIds = [ "text1", "text2", "text3" ];
for ( var i = 0, len = pIds.length; i < len; i++) {
var item = document.getElementById(pIds[i]);
if (item) {
item.className = pID == pIds[i] ? 'unhidden' : 'hidden';
}
}
}
Dropout:其实你并不需要链接,只要能实现功能即可。
HTML
<p onclick="unhide('text1')">Text 1</p>
<p onclick="unhide('text2')">Text 2</p>
<p onclick="unhide('text3')">Text 3</p>
<p id="text1" class="unhidden">
This will show up when the Text 1 link is pressed.
</p>
<p id="text2" class="hidden">
This will show up when the Text 2 link is pressed.
</p>
<p id="text3" class="hidden">
This will show up when the Text 3 link is pressed.
</p>
JS
function unhide(id){
yourElement = document.getElementById(id);
if(yourElement.className == "unhidden"){
yourElement.className = "hidden";
}else{
yourElement.className = "unhidden";
}
}