Почему моя функция javascript не работает по всей странице - PullRequest
0 голосов
/ 05 февраля 2019

Я пытаюсь настроить раздел на своем сайте, чтобы использовать кнопки переключения, которые будут расширять абзац.Проблема в том, что функция работает на первой кнопке, но любая кнопка после этого не работает.Есть идеи?

Вот мой сценарий

$(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. (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 id="toggle">Read More</button>
</div>

Ответы [ 4 ]

0 голосов
/ 05 февраля 2019

Вы правильно поняли идею, но при ее реализации все пошло не так.правильно использовать класс -> $ (". toggle"). click (function () {});но внутри вы используете класс как id здесь -> $ ("# toggle"). text ();и $ (". toggle"). text ("Read Less"); $ ("# text"). slideDown ();и т. д. Вместо этого попробуйте использовать вместо этого $ (this) и $ (this) .find ('# text').

0 голосов
/ 05 февраля 2019

Вы ссылаетесь на элемент по ID, но идентификаторы должны быть уникальными для каждого элемента DOM.

Если вы хотите сослаться на несколько элементов, вы должны сделать это через класс.

Вам также нужноизменить способ ссылки на элемент в функции щелчка.Использование this гарантирует, что вы вносите изменения в текущий элемент (по нажатию), а не в любой элемент, соответствующий вашему выбору.

Чтобы иметь возможность управлять другим элементом, связанным с триггером, я 'Я предлагаю вам обернуть их в родительский элемент (например, div), чтобы позволить вам надежно определить конкретный элемент, который вы хотите скользить.

<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();
    }
  });
});
0 голосов
/ 05 февраля 2019

Возможно, у вас есть повторяющиеся идентификаторы

Вместо этого используйте класс и относительную адресацию

Также используйте DIV вместо диапазонов

$(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. (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>
</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. (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>
</div>
<div class="btn-container">
  <button type="button">Read More</button>
</div>
0 голосов
/ 05 февраля 2019

Вы используете id="toggle" для ссылки на кнопки.Идентификаторы должны быть уникальными.Вот почему ваш селектор возвращает только первое значение.Чтобы это исправить, просто измените id на class примерно так:

$(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. (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>

Вам потребуется изменить селектор для текстового элемента, если вы хотите, чтобы кнопка управляла своим собственным текстовым элементом.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...