用于多个动作的javascript函数

时间:2013-05-13 21:43:01

标签: javascript

如果我使用这个JS代码:

<script language="javascript" type="text/javascript">
     function showHideDiv()
    {
        var divstyle = new String();
        divstyle = document.getElementById("elementId").style.visibility;
        if(divstyle.toLowerCase()=="visible" || divstyle == "")
        {
            document.getElementById("elementId").style.visibility = "hidden";
        }
        else
        {
            document.getElementById("elementId").style.visibility = "visible";
        }
    }
</script>

然后这是我的HTML:

<a href="#" class="Action" id="action" onclick="return showHideDiv();">Menu</a>
    <div id="elementId" style="visibility:hidden">
     content here
     </div>

将另一个div扩展为div但没有多个函数的最佳方法是什么?

2 个答案:

答案 0 :(得分:0)

只需添加一个函数参数:

function showHideDiv(id)
{
    var element = document.getElementById(id),
    visibility = element.style.visibility.toLowerCase(),
    isVisible = visibility === "visible" || visibility === "";

    element.style.visibility = isVisible ? 'hidden' : 'visible';
}

然后在你的HTML中,你传递它:

onclick="showHideDiv('elementId');"

Demo

答案 1 :(得分:-1)

尝试:

function toggleDiv(showDiv) {
    var elm, divstyle, isHidden;
    elm = document.getElementById("elementId");
    divstyle = elm.style.visibility;
    isHidden = divstyle.toLowerCase() == "visible" || divstyle == "" ? false : true;
    elm.style.visibility = (showDiv === true || (isHidden && showDiv !== false) ? 'visible' : 'hidden')
}

用法:

toggleDiv() // Toggles visibility to opposite of current state.
toggleDiv(true) // Always shows div.
toggleDiv(false) // Always hides div.

小提琴:http://jsfiddle.net/d2jkq/