javascript - 如何修复 jquery/javascript 值未在 html 中第二次显示
问题描述
我正在尝试使用以下脚本在 HTML 页面中多次使用 year
$('#year').text(new Date().getFullYear());
它第一次显示,但第二次无法正常工作。我在 html 中使用下面的代码
<p>Copyright ©
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 ©
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>
解决方案
不能有两个具有相同 ID 的元素,但可以使用相同的类。
<p>Copyright ©
First Time<span class="year"></span> - Second Time<span class="year"></span>
</p>
$('.year').text(new Date().getFullYear());
推荐阅读
- javascript - 我可以在异步函数内的 javascript 中创建一个 html 片段吗?
- javascript - 我可以获得 mui SvgIcon 组件的实时示例吗?
- c - 尝试获取文件的最后修改时间会更改时间戳
- mongodb - mongo_dart:未为 () 实现
- reactphp - ReactPHP 异步承诺
- google-cloud-functions - 如何更改默认的云功能打开遥测导出器?
- parsing - 自顶向下解析器的类型
- fivetran - 使用 Fivetran 将 csv 文件上传到雪花
- python - Pandas 系列将值拆分为列
- python - Pandas 从 csv 读取字节字符串