【问题标题】:Why is my JavaScript/JQuery adding and removing class with function not working?为什么我的 JavaScript/JQuery 添加和删除带有函数的类不起作用?
【发布时间】:2020-12-12 17:14:26
【问题描述】:

大家好,我今天遇到了大问题。

当用户在字段中输入文本然后按下提交时,用户输入的文本应该出现在图像下方的标题上,之前是.invisible,但是当用户按下提交时我使用 jquery 将其删除。我还使用.html 将html 更改为用户的文本输入。我已经标记了这部分(见评论:// Displaying captions that user chose in javascript)。

但是这并没有发生...有人可以帮忙谢谢...

这是我的 javascript:

    function diceRoll() {
  // 1st dice
  var randomNumber1 = Math.floor(Math.random() * 6 + 1);
  var Image1 = "dice" + randomNumber1 + ".png";
  document.querySelectorAll("img")[1].setAttribute("src", Image1);

  // 2nd dice
  var randomNumber2 = Math.floor(Math.random() * 6 + 1);
  var Image2 = "dice" + randomNumber2 + ".png";
  document.querySelectorAll("img")[2].setAttribute("src", Image2);

  // 3rd dice
  var randomNumber3 = Math.floor(Math.random() * 6 + 1);
  var Image3 = "dice" + randomNumber3 + ".png";
  document.querySelectorAll("img")[3].setAttribute("src", Image3);

  // 4th dice
  var randomNumber3 = Math.floor(Math.random() * 6 + 1);
  var Image4 = "dice" + randomNumber3 + ".png";
  document.querySelectorAll("img")[4].setAttribute("src", Image4);
}


// Responding to Dropdown Button
let links = document.querySelectorAll('#list li')
links.forEach((el) => {
  el.addEventListener('click', (event) => {
    let numberOfChoices = event.target.innerText
    document.getElementById('dropdownMenu').innerHTML = `${numberOfChoices}<span class="caret"></span>`

    if (numberOfChoices === "2") {
      $("#img3, #img4, .threeChoices, .fourChoices").addClass("invisible")
    }
    if (numberOfChoices === "3") {
      $("#img4, .fourChoices").addClass("invisible");
      $("#img3, .threeChoices").removeClass("invisible")
    }
    if (numberOfChoices === "4") {
      $("#img3, #img4, .threeChoices, .fourChoices").removeClass("invisible");
    }
  })
})

// Responding to Submit
document.getElementById("submit").addEventListener("click", function(e) {
  e.preventDefault();

// Storing Data into variables
  var choice1 = $("#choice1").val();
  var choice2 = $("#choice2").val();
  var choice3 = $("#choice3").val();
  var choice4 = $("#choice4").val();
  var noOfChoices = $("#dropdownMenu").text();

// Rotate animation
  $(".dice").addClass("rotate");

// Changing text to user input
      $("#caption1").html(choice1);
      $("#caption2").html(choice2);
      $("#caption3").html(choice3);
      $("#caption4").html(choice4);

// Displaying captions that user chose
    if (noOfChoices === "2") {
      $("#caption1, #caption2").removeClass("invisible");
      $("#caption3, #caption4").addClass("invisible");
    }

    if (noOfChoices === "3") {
      $("#caption1, #caption2, #caption3").removeClass("invisible");
      $("#caption4").addClass("invisible");
    }

    if (noOfChoices === "4") {
      $(".caption").removeClass("invisible");
    }

// Rolling Dice
  diceRoll();

// Determining winner


})


var diceNumbers = []

这是我的html:

   <!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>Diceey</title>

  <!-- Bootstrap, CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
  <link rel="stylesheet" href="styles.css">

  <!-- Jquery Links -->
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</head>

<body>
    
      <!-- Images -->
  <div class="container-fluid">

    <div class="container-of-images">
      <img src="chick2.png">

      <figure>
        <img id="img1" class="dice" src="dice6.png">
        <figcaption class="caption" id="caption1">Choice 1</figcaption>
      </figure>

      <figure>
        <img id="img2" class="dice" src="dice6.png">
        <figcaption class="caption" id="caption2">Choice 2</figcaption>
      </figure>

      <figure class="threeChoices">
        <img id="img3" class="dice" src="dice6.png">
        <figcaption class="caption" id="caption3">Choice 3</figcaption>
      </figure>

      <figure class="fourChoices">
        <img id="img4" class="dice" src="dice6.png">
        <figcaption class="caption" id="caption4">Choice 4</figcaption>
      </figure>
      <img src="chick1.png">
    </div>
  </div>


<!-- Forms -->

<div class="container-fluid">

    <h5>Write down your choices here (up to 4):</h5>
  <div class="container-of-forms">

    <!-- Dropdown Button -->
    <div class="dropdown">
      <button class="btn btn-info dropdown-toggle" type="button" id="dropdownMenu" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
        2
        <span class="caret"></span>
      </button>
      <ul id="list" class="dropdown-menu dropdown-info" aria-labelledby="dropdownMenu">
        <li><a href="#">2</a></li>
        <li><a href="#">3</a></li>
        <li><a href="#">4</a></li>
      </ul>

      <!-- Input Text Fields -->
      <div class="container-inner">
        <input class="text-input-box" id="choice1" type="text" name="" value="" placeholder="Choice 1"> <br>
        <input class="text-input-box" id="choice2" type="text" name="" value="" placeholder="Choice 2"> <br>
        <input class="text-input-box invisible threeChoices" id="choice3" type="text" name="" value="" placeholder="Choice 3"> <br>
        <input class="text-input-box invisible fourChoices" id="choice4" type="text" name="" value="" placeholder="Choice 4">
      </div>
    </div>



  </div>
  <!-- Submit Button -->
  <a href="" id="submit" class="btn btn-info btn-lg" role="button">Go</a>
</div>

  <script src="index.js" charset="utf-8">
  </script>
</body>
</html>

这是我的 CSS:

img {
  width: 80px;
  line-height: 0;
  margin: 0 1%;
  display: inline-block;
  justify-content: center;
  vertical-align: middle;
}

figcaption {
  text-align:
    center;
  width: 100px;
  font-size: 1.5rem;
  color: #5b8c85;
  font-family: 'Indie Flower', cursive;
}

figure {
  display: inline-block;
  vertical-align: middle;
}

.rotate {
  animation: rotation 0.3s infinite linear;
  animation-iteration-count: 2;
}

@keyframes rotation {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(359deg);
  }
}

.invisible {
  display: none;
}

.hidden {
  visibility: hidden;
}

【问题讨论】:

  • 你检查过$("#dropdownMenu").text();里面有什么吗?

标签: javascript html jquery css bootstrap-4


【解决方案1】:

从改变这个开始

var noOfChoices = $("#dropdownMenu").text();

var noOfChoices = $("#dropdownMenu option:selected").text();

从下拉框中获取文本。尝试

【讨论】:

  • 但我之前可以使用var noOfChoices = $("#dropdownMenu").text(); 记录 noOfChoices。我不知道出了什么问题,响应下拉按钮曾经工作过
  • 如果您使用的是 Chrome,请尝试检查控制台。您将收到一些关于某些 getElementById 的错误,因为您使用的 id 不存在。 - document.getElementById('dropdownMenu1').innerHTML = ${numberOfChoices}&lt;span class="caret"&gt;&lt;/span&gt;
【解决方案2】:

我运行了您的代码,看来将 var noOfChoices = $("#dropdownMenu").text() 更改为 var noOfChoices = $("#dropdownMenu").text().trim() 就可以了。

不知何故,下拉菜单 text() 会在开头有空格,这就是为什么你所有的 if 语句总是返回 false。

这应该是带有一些其他修改的 js 代码,您会发现它们已被注释。

// Responding to Dropdown Button
let links = document.querySelectorAll("#list li");
links.forEach((el) => {
  el.addEventListener("click", (event) => {
    let val = event.target.innerText;
    document.getElementById(
      "dropdownMenu"
    ).innerHTML = `${val}<span class="caret"></span>`;

    if (val === "2") { /* numberOfChoices changed to val */
      $("#img3, #img4, .threeChoices, .fourChoices").addClass("invisible");
    }
    if (val === "3") { /* numberOfChoices changed to val */
      $("#img4, .fourChoices").addClass("invisible");
      $("#img3, .threeChoices").removeClass("invisible");
    }
    if (val === "4") { /* numberOfChoices changed to val */
      $("#img3, #img4, .threeChoices, .fourChoices").removeClass("invisible");
    }
  });
});

// Responding to Submit
document.getElementById("submit").addEventListener("click", function (e) {
  e.preventDefault();

  // Storing Data into variables
  var choice1 = $("#choice1").val();
  var choice2 = $("#choice2").val();
  var choice3 = $("#choice3").val();
  var choice4 = $("#choice4").val();
  var noOfChoices = $("#dropdownMenu").text().trim(); /* adding .trim() here */

  // Rotate animation
  $(".dice").addClass("rotate");
  setTimeout(() => {
    $(".dice").removeClass("rotate");
  }, 1000);

  // Changing text to user input
  $("#caption1").html(choice1);
  $("#caption2").html(choice2);
  $("#caption3").html(choice3);
  $("#caption4").html(choice4);

  // Displaying no. of Captions that User Chose
  if (noOfChoices === "2") {
    $("#caption1, #caption2").removeClass("invisible");
    $("#caption3, #caption4").addClass("invisible");
  }

  if (noOfChoices === "3") {
    $("#caption1, #caption2, #caption3").removeClass("invisible");
    $("#caption4").addClass("invisible");
  }

  if (noOfChoices === "4") {
    $(".caption").removeClass("invisible");
  }

  // Rolling Dice
  diceRoll();
});

【讨论】:

  • 谢谢,我自己解决了大部分问题(我将更新问题中的代码),现在唯一不起作用的是“//显示用户的字幕数量选择”,正如我在 javascript 中注释掉的那样。你知道为什么它不工作吗?非常感谢
  • 是的,这就是我附加的代码的作用。您的问题是 noOfChoices 有空格,这就是为什么您应该使用 trim() 摆脱空格,以便您的任何 if(noOfChoicess === 语句返回 true
  • 你可以查看我写的代码here。检查第34行trim()的使用
猜你喜欢
  • 2014-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-10
  • 1970-01-01
  • 1970-01-01
  • 2014-02-04
相关资源
最近更新 更多