繁体   English   中英

使用 JavaScript 写入 HTML 标签的多个实例仅写入第一个标签

[英]Writing to multiple instances of HTML tag with JavaScript only writes to first tag

我需要一些帮助来弄清楚这里发生了什么。 我有一个正在设置打印的 HTML 文档,但是页面计数器让我头疼。 这是给我问题的代码:

 <html> <head> <style type="text/css">.page { width: 8in; height: 1in; padding: 0em; margin-top: .5in; margin-left: 0in; margin-right: 0in; margin-bottom: 0.25in; } body { color: black; counter-reset: pagen; font-family: "Courier New", Courier, monospace; font-size: 10pt; }.footer { counter-increment: pagen; margin: auto; width: 8in; display: table; } #footer-left:before { content: "Page " counter(pagen) " of "; }.ptable { page-break-before: always; page-break-inside: avoid; } </style> </head> <body> <div class="page"> <div class="footer"> <div id="footer-left"><span id="total"></span></div> </div> </div> <div class="page"> <table class="ptable"></table> <div class="footer"> <div id="footer-left"><span id="total"></span></div> </div> </div> </body> <script type ="text/javascript"> function pageCount() { return document.getElementsByClassName('page').length; } document.getElementById("total").innerHTML = pageCount(); </script> </html>

footer-left的第一个实例将 output 正确地作为Page 1 of 2 第二个实例仅显示Page 2 of 这里发生了什么? 作为参考,我将此文档设置为由基于查询 output 的 VBA 脚本自动生成,因此根据查询的大小,总页数可能会发生变化:封面页 + 数据页。

如果您使用了验证器,您的问题将被突出显示。

id在文档中必须是唯一的。

错误恢复意味着getElementById获得第一个匹配项。

如果您想要一元素而不是唯一标识单个元素,请使用class

您有无效的重复id属性,请改用 class 属性,也使用document.querySelectorAll () 到 select 元素,这是一个工作片段:

 <html> <head> <style type="text/css">.page { width: 8in; height: 1in; padding: 0em; margin-top: .5in; margin-left: 0in; margin-right: 0in; margin-bottom: 0.25in; } body { color: black; counter-reset: pagen; font-family: "Courier New", Courier, monospace; font-size: 10pt; }.footer { counter-increment: pagen; margin: auto; width: 8in; display: table; } #footer-left:before { content: "Page " counter(pagen) " of "; }.ptable { page-break-before: always; page-break-inside: avoid; } </style> </head> <body> <div class="page"> <div class="footer"> <div id="footer-left"><span class="total"></span></div> </div> </div> <div class="page"> <table class="ptable"></table> <div class="footer"> <div id="footer-left"><span class="total"></span></div> </div> </div> </body> <script type ="text/javascript"> function pageCount() { return document.getElementsByClassName('page').length; } document.querySelectorAll(".total").forEach(function(el, i){ el.innerHTML = pageCount(); }); </script> </html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM