0

这是我的 javascript,它工作得很好,除了如果你点击相同的链接两次它会切换。我怎样才能防止这种情况发生?最终,我只想根据单击的项目显示一个部分...但是如果您单击它两次,它会切换。

current = "intersitial"; // div with id="m0" is currently diplayed
function show_or_hide ( id )
{
    if ( current ) //if something is displayed
    {   
        document.getElementById ( current ).style.display = "none";
        if ( current == id ) //if <div> is already diplayed
        {                           
            current = 0;
        }
        else
        {
            document.getElementById ( id ).style.display = "block";
            current = id;
        }
    }
    else //if nothing is displayed
    {
        document.getElementById ( id ).style.display = "block";
        current = id;
    }
}

我的 HTML 是:

<ul>
     <li onclick="show_or_hide('intersitial')"><span>intersitial</span></li>
     <li onclick="show_or_hide('advancedDetail')"><span>advancedDetail</span></li>
     <li onclick="show_or_hide('ultimateDetail')"><span>ultimateDetail</span></li>
</ul>

<div class="megamenu" id="intersitial">intersitial</div>
<div class="megamenu" id="advancedDetail" style="display: none">advancedDetail</div>
<div class="megamenu" id="ultimateDetail" style="display: none">ultimateDetail</div>
4

2 回答 2

1

我建议从突兀的 JavaScript 更改(使用内联事件处理程序、、onclick等),而是使用 JavaScript 来绑定事件:onfocusonblur

// use a function-name that's descriptive of what it does:
function showOnly() {
    // or you could use `document.getElementsByClassName('megamenu'):
    var divs = document.querySelectorAll('div.megamenu'),
        // gets the text from the 'span' of the clicked 'li' (the 'id' for later):
        id = this.firstChild.textContent;
    // iterates over each of the found '.megamenu' elements:
    for (var i = 0, len = divs.length; i < len; i++){
        /* if the id of the current 'div' is the same as the text in the 'span'
           display = block, otherwise display = none:
        */
        divs[i].style.display = divs[i].id === id ? 'block' : 'none';
    }
}

// get the 'li' elements:
var lis = document.querySelectorAll('li');

// iterate over those elements and bind an event-handler to them:
for (var i = 0, len = lis.length; i < len; i++) {
    lis[i].addEventListener('click', showOnly);
}

JS 小提琴演示

这种方法还避免了在全局命名空间中乱扔变量(这些变量很容易在其他函数中被覆盖,特别是(但不完全是)当多个开发人员在同一个项目上工作时)。

参考:

于 2013-11-02T21:05:20.713 回答
0
function show_or_hide(id)
{
    if (current == id) return;
    if (current) // if something is displayed
    {   
        document.getElementById ( current ).style.display = "none";
    }  
    document.getElementById ( id ).style.display = "block";
    current = id;
}
于 2013-11-02T20:32:26.653 回答