简体   繁体   中英

toggle text by clicking on hyperlink

I need to toggle the text on/Off in html without hiding any of the disabled functions. The following code can toggle on and off but the problem is this:

  • It cannot toggle without hiding another word. Ie when I press turn on it hides The Turn Off function.
  • When I add the toggle method for another line item it only toggles the first line item. So it doesn't matter if I add it to line items five rows past the original it will only trigger the original.

 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> 

What am I doing wrong?

First of all some annotation to your code:

IDs have to be unique ! So use classes instead.

I hope I understand it correctly what you are trying to achieve:

HTML:

<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>

JS

$('.displayText').on('click', function(e) {

  $(this).text(function(i, s) {
      return s === 'On' ? 'Off' : 'On';
    });

});

Example


Reference:

.text()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM