javascript - 无法使用 Javascript 更改 span 元素的文本

标签 javascript jquery html css

我有一个 index.html,其中有一个游戏状态窗口,它显示您收集的糖果和珠子的数量,并在用户与糖果碰撞时实时更新和珠子。

我的整个index.html: 另外,status-window div 位于底部。这就是我展示糖果和珠子的地方。其余标记用于游戏窗口。

<html>

<title>Mardi Gras Parade!</title>

<!-- JS -->
<script src='scripts/jquery.min.js'></script>
<script src='scripts/page.js'></script>

<!-- CSS -->
<link rel="stylesheet" type="text/css" href="style/style.css">

<!-- HTML -->
<body>
  <div class='outer-container'>
    <div class='game-window'>
      <div id="actualGame">
        <div id='player' class='playerObject'>
          <img class='player-avatar' src='img/person.png' height='50px'/> <!--person img: src='https://www.google.com/imgres?imgurl=http%3A%2F%2Fclipart-library.com%2Fnew_gallery%2F54-540691_others-clipart-helpful-person-generic-person.png&imgrefurl=http%3A%2F%2Fclipart-library.com%2Fclip-art%2F54-540691_others-clipart-helpful-person-generic-person.htm&tbnid=V19QgOYn0jYyzM&vet=12ahUKEwidx5GevcrnAhUJ0KwKHQynD9AQMygBegUIARCJAg..i&docid=hVn27RN51ga3yM&w=920&h=830&q=person&hl=en&ved=2ahUKEwidx5GevcrnAhUJ0KwKHQynD9AQMygBegUIARCJAg'-->
        </div>
        <div id="paradeRoute">
            <div id="dottedLine"></div>
            <div id="paradeFloats">
              <div id="paradeFloat1" class='paradeFloat'>
                <img src='img/parade_float_1.gif' height='80px'/> <!-- src: https://www.google.com/imgres?imgurl=https%3A%2F%2Fcdn.clipart.email%2Fb0a85a880dc856c8129f51d506469510_mardi-gras-background-transparent-png-clipart-free-download-ywd_474-256.gif&imgrefurl=https%3A%2F%2Fwww.clipart.email%2Fclipart%2Ftransparent-background-mardi-gras-float-clipart-231098.html&tbnid=QDcU0K_06jcQJM&vet=12ahUKEwj40aPwwsrnAhUFgK0KHU4qCkQQMygEegUIARDsAQ..i&docid=7_c8q7QtWx89bM&w=474&h=256&q=mardi%20gras%20parade%20clip%20art&hl=en&client=firefox-b-1-e&ved=2ahUKEwj40aPwwsrnAhUFgK0KHU4qCkQQMygEegUIARDsAQ -->
              </div>
              <div id="paradeFloat2" class='paradeFloat'>
                <img src='img/parade_float_2.png' height='80px'/> <!-- Adapted from src: https://www.google.com/imgres?imgurl=https%3A%2F%2Fcdn.clipart.email%2F2075f16e1c812d5ba8ecece2b6924d75_mardi-gras-clipart-at-getdrawingscom-free-for-personal-use-_340-270.jpeg&imgrefurl=https%3A%2F%2Fwww.clipart.email%2Fclipart%2Fmardi-gras-float-clip-art-228088.html&tbnid=_LNqQJQgyaHKcM&vet=12ahUKEwj40aPwwsrnAhUFgK0KHU4qCkQQMygLegUIARD7AQ..i&docid=Fv4gfo44aw_StM&w=340&h=270&q=mardi%20gras%20parade%20clip%20art&hl=en&client=firefox-b-1-e&ved=2ahUKEwj40aPwwsrnAhUFgK0KHU4qCkQQMygLegUIARD7AQ -->
              </div>
            </div>
        </div>
      </div>
    </div>

    <div class='status-window' style='text-align: center'>
      <h3>Welcome!</h3>
      <hr>
      <br>
      <p>Score:</p>
      <h1 id='score-box'>0</h1>
      <br/>
      <div>
        <b># of beads collected:</b>
        <span id="beadsCounter">0</span>
      </div>
      <div>
        <b># of candy pieces collected:</b>
        <span id="candyCounter">0</span>
      </div>
    </div>
  </div>
</body>

</html>

用收集的糖果和珠子的数量更新 #beadsCounter#candyCounter 应该非常简单,您应该能够这样做:(其中 numCandy 是一个整数,我在逻辑中递增)。代码确实进入了 if-else block ,但当我尝试为两者打印 textContent 时出错。

let numBeads = 0;
let numCandy = 0;

// functions that check when candy and user collide
function checkCollisions() {
  // First, check for rocket-asteroid checkCollisions
  $('.throwingItem').each( function() {
    let curItem = $(this);  // define a local handle for this rocket
    let curItemID = $(this).attr('id');
    let curItemClass = $(this).attr('class');

    if (isColliding($(this) , player)) {
      // add yellow aura here
      document.getElementById(curItemID).classList.add('yellowaura');

      // after 1 second it'll fade from collision
      $(this).fadeTo(1000, 0, function() {
        $(this).remove();

        // update score
        gwhScore.html(parseInt($('#score-box').html()) + SCORE_UNIT);

        console.log($(this).attr('class'));
        // update # of beads collected or candy collected
        if ($(this).attr('class') == 'throwingItem beads yellowaura') {
          numBeads++;
          console.log(numBeads);
          console.log(document.getElementById('#beadsCounter').textContent);
          document.getElementById('#beadsCounter').textContent = toString(numBeads);
        }
        else {
          numCandy++;
          console.log(numCandy);
          console.log(document.getElementById('#candyCounter').textContent);
          document.getElementById('#candyCounter').textContent = toString(numCandy);
        }
      })
    }
  });
}

但是,这不适用于糖果或珠子,控制台告诉我:

page.js:130 Uncaught TypeError: Cannot read property 'textContent' of null
    at HTMLDivElement.<anonymous> (page.js:130)
    at HTMLDivElement.e.complete (jquery.min.js:3)
    at i (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at i (jquery.min.js:3)
    at Function.r.fx.tick (jquery.min.js:3)
    at ab (jquery.min.js:3)

此外,我已经尝试使用 innerHTML 而不是 textContent 进行此操作,但它不起作用。我试过这个JSFiddle并确认它应该有效,但它不适合我。

对于糖果和珠子的数量,textContent 最初设置为 0,因此它不为空。

最佳答案

由于 getElementById 将参数值视为 id,因此您无需在 id 字符串前添加符号 #:

document.getElementById('candyCounter').textContent

请注意:使用 querySelector() API 时必须添加符号 (#) 前缀:

document.querySelector('#candyCounter').textContent

关于javascript - 无法使用 Javascript 更改 span 元素的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60534026/

相关文章:

javascript - 在 JavaScript 中创建元素或在 CSS 中隐藏元素

javascript - 访问系统光标图像形式的JavaScript

javascript - 我们可以在浏览器 session 中跨网页引用 JavaScript 变量吗?

html - 选择不同 parent 类(class)的第一个 child

javascript - 为什么这被认为是 "good"的 promise 保证?

Javascript 调用 Function() 来创建一个函数

javascript - 使用 Laravel/Ajax 混淆 javascript 中的请求 url

javascript - 转换时间 00 :30:20 format to string

javascript - 添加和显示图像

javascript - 当鼠标悬停在 div 1 上时,取决于它是否在 div 2 上,它应该有不同的行为