我使用此代码进行切换:
<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。 如何在同一篇文章中使用多次此切换而不会发生冲突?
答案 0 :(得分: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>
答案 1 :(得分:0)
下面的代码解决了保持开放的拳头切换问题。谢谢Nibra!
<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>