1

我将此代码用于切换:

    <script language="javascript"> 
function toggle() {
    var ele = document.getElementById("toggleText");
    var text = document.getElementById("displayText");
    if(ele.style.display == "block") {
            ele.style.display = "none";
        text.innerHTML = "show";
    }
    else {
        ele.style.display = "block";
        text.innerHTML = "hide";
    }
} 
</script>

<a id="displayText" href="javascript:toggle();">show</a> 
<div id="toggleText" style="display: none"><h1>OPEN</h1></div>

我尝试在我网站上的同一篇文章中多次使用此切换,但它不起作用。我没有使用 jQuery,而只使用了 javascript。如何在同一篇文章中多次使用此切换而不发生冲突?

4

2 回答 2

2

仅仅添加一个数字是不够的。为了使 toggle() 函数适用于不同的元素,您必须向该函数提供有关它们的信息:

<script type="text/javascript"> 
function toggle(id, link) {
    var elem = document.getElementById(id);
    var text = document.getElementById(link);
    if (elem.style.display != "none") {
        elem.style.display = "none";
        text.innerHTML = "show";
    } else {
        elem.style.display = "block";
        text.innerHTML = "hide";
    }
} 
</script>

<ul>
    <li>
        <a id="displayText" href="javascript:toggle('toggleText', 'displayText');">hide</a> 
        <div id="toggleText" style="display: block"><h1>OPEN</h1></div>
    </li>
    <li>
        <a id="toggler2" href="javascript:toggle('secondText', 'toggler2');">show</a> 
        <div id="secondText" style="display: none"><h1>OPEN</h1></div>
    </li>
</ul>
于 2013-03-31T02:27:40.220 回答
0

下面的代码解决了保持打开状态的第一个切换问题。谢谢尼布拉!

<script type="text/javascript">
    // <![CDATA[
    function toggle(id, link) {
        var elem = document.getElementById(id);
        var text = document.getElementById(link);
        if (elem.style.display != "none") {
            elem.style.display = "none";
            text.innerHTML = "show";
        } else {
            elem.style.display = "block";
            text.innerHTML = "hide";
        }
    }
    // ]]>

</script>
<ul>
    <li><a id="displayText" href="javascript:toggle('toggleText', 'displayText');">show</a>
        <div id="toggleText" style="display: none;">
            <h1>OPEN</h1>
        </div></li>
    <li><a id="toggler2" href="javascript:toggle('secondText', 'toggler2');">show</a>
        <div id="secondText" style="display: none;">
            <h1>OPEN</h1>
        </div></li>
    <li><a id="toggler3" href="javascript:toggle('thirdText', 'toggler3');">show</a>
        <div id="thirdText" style="display: none;">
            <h1>OPEN</h1>
        </div></li>
    <li><a id="toggler4" href="javascript:toggle('forthText', 'toggler4');">show</a>
        <div id="forthText" style="display: none;">
            <h1>OPEN</h1>
        </div></li>
</ul>
于 2013-04-05T11:39:34.053 回答