我需要在html中切换文本on / Off,而不隐藏任何禁用的功能。以下代码可以切换on
和off
,但问题是:
function toggle() {
var ele = document.getElementById("toggleText");
var text = document.getElementById("displayText");
if (ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "On";
} else {
ele.style.display = "block";
text.innerHTML = "Turn Off";
}
}
<h1>Services</h1>
<h2>Subscribed Services</h2>
<ul>
<li>Geolocation -<a id="displayText" href="javascript:toggle();">On</a>
<div id="toggleText" style="display: none"></div>
</li>
<li>E-Mail Messaging -<a id="displayText" href="javascript:toggle();">On</a>
<div id="toggleText" style="display: none"></div>
</li>
</ul>
我做错了什么?
答案 0 :(得分:1)
首先是代码的一些注释:
ID必须为unique!所以请改用类。
我希望我能正确理解你想要实现的目标:
HTML:
<div class="block">
<h3>Something</h3>
<br>
<h4>Some other heading</h4>
<br>
<h4>Some other heading</h4>
<br>
<h4>Some other heading</h4>
</div>
JS
<h2>Subscribed Services</h2>
<ul>
<li>Geolocation -<a class="displayText" href="javascript:void(0);">On</a>
</li>
<li>E-Mail Messaging -<a class="displayText" href="javascript:void(0);">On</a>
</li>
</ul>
参考: