如何生成指定长度的字母数字随机字符串并插入HTML <span>标签?
Fixes for Random String Generation and Placement
Key Issues Addressed
- Barcode string appearing at page top: Replaced
document.write()with targeting the specific#barcodespan element. - AUTH/TOKN only generating numbers: Updated the
showRandomNumberfunction to use the existingrandomStringutility with a lowercase alphanumeric character set. - Ensured DOM readiness: Wrapped execution code in
DOMContentLoadedto avoid element access errors.
Corrected JavaScript Code
function showRandomNumber() { const lowerAlphaNumeric = '0123456789abcdefghijklmnopqrstuvwxyz'; document.getElementById("authnumber").innerHTML = randomString(10, lowerAlphaNumeric); document.getElementById("tokennumber").innerHTML = randomString(10, lowerAlphaNumeric); } function randomString(length, chars) { let result = ''; for (let i = length; i > 0; --i) { result += chars[Math.round(Math.random() * (chars.length - 1))]; } return result; } // Execute once the DOM is fully loaded document.addEventListener('DOMContentLoaded', function() { const fullAlphaNumeric = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; document.getElementById("barcode").innerHTML = randomString(36, fullAlphaNumeric); showRandomNumber(); });
Corrected HTML (minor fix for font color)
<div class="warning_menu_container" style="margin-top:7px; margin-bottom:-11px;"> <span id="barcode" style="margin-top:-7px; ">insert random string of text here 01</span> <span id="myNumber">AUTH:<font color="#1fa779"><span id="authnumber" style="align:right;"></span></font> </span><br /> <span id="myNumber" style="line-height: 1.1;">TOKN:<font color="#1fa779"><span id="tokennumber"></span></font> </span> </div>
CSS (no changes needed)
#barcode { font-family: "Code 128"; font-size: 44.5px; display: inline-block; -moz-transform: scaleY(.73); -webkit-transform: scaleY(.73); transform: scaleY(.73); float: left; } #myNumber { margin: 2px; font-family: "OCR A Extended", "OCR A"; font-size: 16.75px; margin-top: 6.5px; }
Explanation of Changes
- Barcode Placement: Using
document.getElementById("barcode").innerHTMLdirectly inserts the 36-character string into the intended span instead of writing to the top of the page withdocument.write(). - AUTH/TOKN String Generation: The
showRandomNumberfunction now callsrandomStringwith a character set containing digits and lowercase letters, producing the required 10-character alphanumeric strings. - DOM Readiness: Wrapping the execution code in
DOMContentLoadedensures that all HTML elements are available before the JavaScript tries to modify them, preventing "element not found" errors.
内容的提问来源于stack exchange,提问作者Justin Reever
相关产品推荐
相关产品推荐

