单击原始元素或其他元素以切换可见性

时间:2016-09-15 00:08:44

标签: javascript html

所以我有一个函数在调用时使元素可见:

<a class="button" href="#" onclick="toggle_visibility('first');">Button</a>
<a class="url" id="first" href="#">First</a>
<a class="button" href="#" onclick="toggle_visibility('second');">Button2</a>
<a class="url" id="second" href="#">Second</a>
{
    "FooBar": {
        "root": {
            "name": "test1",
            "value": "900",
            "childABC": {
                "name": "test2",
                "value": "700",
                "childXYZ": {
                    "name": "test3",
                    "value": "600"
                }
            },
            "childAnyRandomName": {
                 "name": "test4",
                 "value": "300"
            }
        }
    }
}

这是有效的,但我想要的是,如果我将该函数用于不同的id,则可以切换元素。因此,如果我首先在#first上切换,然后在#second上切换,我希望#first切换掉。

3 个答案:

答案 0 :(得分:0)

试试这个:

<a class="button" href="#" onclick="toggle_visibility('first');">Button</a>
<a class="url" style='display:block' id="first" href="#">First</a>
<a class="button" href="#" onclick="toggle_visibility('second');">Button2</a>
<a class="url" style='display:block' id="second" href="#">Second</a>
{{1}}

答案 1 :(得分:0)

这是一种可能的解决方案。

&#13;
&#13;
     function toggle_visibility(id) {
             if (id=='first'){
              var e = document.getElementById(id);
              var f = document.getElementById('second');
               }
       else {var e = document.getElementById(id);
              var f = document.getElementById('first');}
              if(e.style.display == 'block'){
                 e.style.display = 'none';
                 f.style.display= 'block';}
       
              else
                { e.style.display = 'block';
                 f.style.display = 'none';}
              }
&#13;
<a class="button" href="#" onclick="toggle_visibility('first');">Button</a>
    <a class="url" id="first" href="#">First</a>
    <a class="button" href="#" onclick="toggle_visibility('second');">Button2</a>
    <a class="url" id="second" href="#">Second</a>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

你可以试试这个

toggle_visibility = function(id) {
    var all_urls = document.getElementsByClassName('url');
    var e = document.getElementById(id);
    for(var i=0;i<all_urls.length;i++){
      if(all_urls[i].id !== id)
        all_urls[i].style.display= 'none';
    }
    if(e.style.display == 'block')
      e.style.display = 'none';
    else
      e.style.display = 'block';
 }
<a class="button" href="#" onclick="toggle_visibility('first');">Button</a>
<a class="url" id="first" href="#">First</a>
<a class="button" href="#" onclick="toggle_visibility('second');">Button2</a>
<a class="url" id="second" href="#">Second</a>