javascript - 将多个参数传递到单个参数

标签 javascript html

我在互联网上找到了一个显示和隐藏代码片段的脚本:

 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/

相关文章:

javascript - 这是 JavaScript 内存泄漏吗?

javascript - 如何删除 Material 设计中的所有 css 类和 js,以获得默认选择框

javascript - 替换html中的所有单词而不影响标签

javascript - 了解 eval() 的用法来评估 bool 值

javascript - 字母数字字符和 -/only 的正则表达式

jquery - 如何阻止元素在移动设备上调整大小?

html - 同步 css3 转换

javascript - 如何将本 map 片链接到js中的字符串

javascript - JQuery函数返回语句首先被执行,然后只执行里面的条件

javascript - 具有最长字符串长度的所有字符串