首页 > 解决方案 > 如何修复 jquery/javascript 值未在 html 中第二次显示

问题描述

我正在尝试使用以下脚本在 HTML 页面中多次使用 year

$('#year').text(new Date().getFullYear());

它第一次显示,但第二次无法正常工作。我在 html 中使用下面的代码

<p>Copyright &copy;
  First Time<span id="year"></span> - Second Time<span id="year"></span>
</p>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8"> 
  <title>Jquery Date issue</title>
</head>
<body> 
    <p>Copyright &copy;
            First Time<span id="year"></span> - Second Time<span id="year"></span>
    </p>
  <script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
    crossorigin="anonymous"></script>

  <script>
    // Get the current year for the copyright
    $('#year').text(new Date().getFullYear());   
  </script>
</body>

</html>

代码在这里https://jsfiddle.net/vptechworld/z0gmobyw/5/

标签: javascriptjquery

解决方案


不能有两个具有相同 ID 的元素,但可以使用相同的类。

<p>Copyright &copy;
  First Time<span class="year"></span> - Second Time<span class="year"></span>
</p>
$('.year').text(new Date().getFullYear());

推荐阅读