我在互联网上找到了一个显示和隐藏代码片段的脚本:
function show(shown, hidden,) {
document.getElementById(shown).style.display='block';
document.getElementById(hidden).style.display='none';
return false;
}
<a href="#" onclick="return show('Page1','Page2');">Page 1</a>
<a href="#" onclick="return show('Page2','Page1');">Page 2</a>
我的问题是,我该如何更改它以包含更多页面?
我发现唯一可行的方法是:
function show(shown, hidden1, hidden2, hidden3) {
document.getElementById(shown).style.display='block';
document.getElementById(hidden1).style.display='none';
document.getElementById(hidden2).style.display='none';
document.getElementById(hidden3).style.display='none';
return false;
}
<a href="" onclick="return show('Page1','Page2','Page3','Page4' );">Page 1</a>
<a href="" onclick="return show('Page2','Page1','Page3','Page4' );">Page 2</a>
<a href="" onclick="return show('Page3','Page1','Page2','Page4' );">Page 3</a>
<a href="" onclick="return show('Page4','Page1','Page2','Page3' );">Page 4</a>
...不过好像有点乱。那么有没有办法将 3 个页面同时传递到脚本中的“隐藏”参数中?
谢谢!
最佳答案
您可以将数组作为隐藏
参数传递。然后你必须像这样修改你的 JS:
function show(shown, hidden ) {
document.getElementById(shown).style.display='block';
for( var i=hidden.length; i--; ) {
document.getElementById(hidden[i]).style.display='none';
}
return false;
}
HTML 看起来像这样:
<a href="" onclick="return show('Page1', ['Page2','Page3','Page4'] );">Page 1</a>
作为替代方案,您可以使用类而不是设置样式。然后你可以将 hidden
参数一起删除:
function show( shown ) {
// remove class 'shownPage' everywhere
var els = document.querySelectorAll( '.shownPage' );
for( var i=els.length; i--; ) {
els.classList.remove( 'shownPage' );
}
// and just add it to the page to show
document.getElementById(shown).classList.add( 'shownPage' );
return false;
}
关于javascript - 将多个参数传递到单个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14159589/