单击两次时链接切换

时间:2013-11-02 20:17:22

标签: javascript jquery

这是我的javascript,它的效果很好,但如果你点击两次相同的链接就会切换。我该如何防止这种情况发生?最终我只是想根据点击的项目显示一个psection ...但如果你点击它两次它切换。

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>

2 个答案:

答案 0 :(得分:1)

我建议更改突出的JavaScript(使用内联事件处理程序,onclickonfocusonblur等),而是使用JavaScript绑定事件:

// 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 Fiddle demo

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

参考文献:

答案 1 :(得分: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;
}