简体   繁体   中英

Why isn't my javascript function working throughout the page

I'm trying to set a section on my site to use toggle buttons that will expand a paragraph. The problem is, the function is working on the first button, but any button after that is not working. Any ideas?

Here is my script

 $(document).ready(function() { $("#toggle").click(function() { var elem = $("#toggle").text(); if (elem == "Read More") { //Stuff to do when btn is in the read more state $("#toggle").text("Read Less"); $("#text").slideDown(); } else { //Stuff to do when btn is in the read less state $("#toggle").text("Read More"); $("#text").slideUp(); } }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h2>WEIGHT LOSS</h2> <span id="text" style="display: none"><p>Regular sauna use can reduce overall body fat. Near infrared light has been shown to decrease cellulite. NIR heat lamp saunas allow specific problem areas to be targeted as needed. (Eg cellulite in thigh skin). A study involving a group of women riding stationary bicycles demonstrated a 444% increase in weight loss for the group exposed to near infrared light when compared to the exercise only group. Infrared light combined with other therapies has been shown to be effective in controlling cellulite.</p> <p>A two-phase, sauna weight loss study conducted by Binghamton University in New York revealed that an increase in core body temperature resulted in a decrease in body fat. It concluded that people who used an infrared sauna three times a week for 30 minutes per session dropped an average of 4 percent body fat over a four-month period. For a 175-pound man, that represents a weight reduction of seven pounds.</p> <p>Participants who experienced infrared sauna weight loss did not change their exercise or diet patterns during the study. Control groups in the study who did not use the sauna showed no drop in weight. The study findings illustrate the significant boost that infrared therapy provides for our weight loss goals.</p> </span> <div class="btn-container"> <button id="toggle">Read More</button> </div> 

You are using id="toggle" to reference the buttons. Id's must be unique. That is why your selector only returns the first value. To fix this, simply change id to class like so:

 $(document).ready(function() { $(".toggle").click(function() { var elem = $(this).text(); if (elem == "Read More") { //Stuff to do when btn is in the read more state elem.text("Read Less"); $("#text").slideDown(); } else { //Stuff to do when btn is in the read less state elem.text("Read More"); $("#text").slideUp(); } }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h2>WEIGHT LOSS</h2> <span id="text" style="display: none"><p>Regular sauna use can reduce overall body fat. Near infrared light has been shown to decrease cellulite. NIR heat lamp saunas allow specific problem areas to be targeted as needed. (Eg cellulite in thigh skin). A study involving a group of women riding stationary bicycles demonstrated a 444% increase in weight loss for the group exposed to near infrared light when compared to the exercise only group. Infrared light combined with other therapies has been shown to be effective in controlling cellulite.</p> <p>A two-phase, sauna weight loss study conducted by Binghamton University in New York revealed that an increase in core body temperature resulted in a decrease in body fat. It concluded that people who used an infrared sauna three times a week for 30 minutes per session dropped an average of 4 percent body fat over a four-month period. For a 175-pound man, that represents a weight reduction of seven pounds.</p> <p>Participants who experienced infrared sauna weight loss did not change their exercise or diet patterns during the study. Control groups in the study who did not use the sauna showed no drop in weight. The study findings illustrate the significant boost that infrared therapy provides for our weight loss goals.</p> </span> <div class="btn-container"> <button class="toggle">Read More</button> </div> 

You will need to alter the selector for the text element if you intend to have a button control its own text element.

You are referencing an element by ID, but IDs must be unique per DOM element.

When you want to reference multiple elements you should do so via a class.

You also need to change how you reference the element within your on click function. Using this ensures you're making the changes to the current element (the one being clicked) and not any element that matches your selection.

To be able to control another element related to the trigger, I'd suggest you wrapped them in a parent element (like a div ) to let you reliably determine the specific element you want to slide.

<div>
    <h2>WEIGHT LOSS</h2>
    <span class="text" style="display: none"><p>Regular sauna use can reduce overall body fat. Near infrared light has been shown to  decrease cellulite. NIR heat lamp saunas allow specific problem areas to be targeted as needed. (E.g. cellulite in thigh skin). A study involving a group of women riding stationary bicycles demonstrated a 444% increase in weight loss for the group exposed to near infrared light when compared to the exercise only group.  Infrared light combined with other therapies has been shown to be effective in controlling cellulite.</p>

        <p>A two-phase, sauna weight loss study conducted by Binghamton University in New York revealed that an increase in core body temperature resulted in a decrease in body fat. It concluded that people who used an infrared sauna three times a week for 30 minutes per session dropped an average of 4 percent body fat over a four-month period. For a 175-pound man, that represents a weight reduction of seven pounds.</p>

        <p>Participants who experienced infrared sauna weight loss did not change their exercise or diet patterns during the study. Control groups in the study who did not use the sauna showed no drop in weight. The study findings illustrate the significant boost that infrared therapy provides for our weight loss goals.</p>
    </span>
    <div class="btn-container">
      <button class="toggle">Read More</button>
    </div>
$(document).ready(function() {
  $(".toggle").click(function() {
    var elem = $(this).text();
    if (elem == "Read More") {
      //Stuff to do when btn is in the read more state
      $(this).text("Read Less");
      $(this).parent().parent().children('.text').slideDown();
    } else {
      //Stuff to do when btn is in the read less state
      $(this).text("Read More");
      $(this).parent().parent().children('.text')..slideUp();
    }
  });
});

You likely have duplicate IDs

Instead use the class and relative addressing

Also use DIVs instead of spans

 $(function() { $(".btn-container>button").on("click", function(e) { var text = $(this).text(); if (text === "Read More") { //Stuff to do when btn is in the read more state $(this).text("Read Less"); $(this).parent().prev(".text").slideDown(); } else { //Stuff to do when btn is in the read less state $(this).text("Read More"); $(this).parent().prev(".text").slideUp(); } }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h2>WEIGHT LOSS 1</h2> <div class="text" style="display: none"> <p>Regular sauna use can reduce overall body fat. Near infrared light has been shown to decrease cellulite. NIR heat lamp saunas allow specific problem areas to be targeted as needed. (Eg cellulite in thigh skin). A study involving a group of women riding stationary bicycles demonstrated a 444% increase in weight loss for the group exposed to near infrared light when compared to the exercise only group. Infrared light combined with other therapies has been shown to be effective in controlling cellulite.</p> <p>A two-phase, sauna weight loss study conducted by Binghamton University in New York revealed that an increase in core body temperature resulted in a decrease in body fat. It concluded that people who used an infrared sauna three times a week for 30 minutes per session dropped an average of 4 percent body fat over a four-month period. For a 175-pound man, that represents a weight reduction of seven pounds.</p> <p>Participants who experienced infrared sauna weight loss did not change their exercise or diet patterns during the study. Control groups in the study who did not use the sauna showed no drop in weight. The study findings illustrate the significant boost that infrared therapy provides for our weight loss goals.</p> </div> <div class="btn-container"> <button type="button">Read More</button> </div> <h2>WEIGHT LOSS 2 </h2> <div class="text" style="display: none"> <p>Regular sauna use can reduce overall body fat. Near infrared light has been shown to decrease cellulite. NIR heat lamp saunas allow specific problem areas to be targeted as needed. (Eg cellulite in thigh skin). A study involving a group of women riding stationary bicycles demonstrated a 444% increase in weight loss for the group exposed to near infrared light when compared to the exercise only group. Infrared light combined with other therapies has been shown to be effective in controlling cellulite.</p> <p>A two-phase, sauna weight loss study conducted by Binghamton University in New York revealed that an increase in core body temperature resulted in a decrease in body fat. It concluded that people who used an infrared sauna three times a week for 30 minutes per session dropped an average of 4 percent body fat over a four-month period. For a 175-pound man, that represents a weight reduction of seven pounds.</p> <p>Participants who experienced infrared sauna weight loss did not change their exercise or diet patterns during the study. Control groups in the study who did not use the sauna showed no drop in weight. The study findings illustrate the significant boost that infrared therapy provides for our weight loss goals.</p> </div> <div class="btn-container"> <button type="button">Read More</button> </div> 

you have got the idea right, but while implementing it has gone little wrong. using class is right -> $(".toggle").click(function() { }); but inside you are using class like id here -> $("#toggle").text(); and $(".toggle").text("Read Less");$("#text").slideDown(); etc, instead try using $(this) and $(this).find('#text') instead.

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