You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何生成指定长度的字母数字随机字符串并插入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 #barcode span element.
  • AUTH/TOKN only generating numbers: Updated the showRandomNumber function to use the existing randomString utility with a lowercase alphanumeric character set.
  • Ensured DOM readiness: Wrapped execution code in DOMContentLoaded to 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

  1. Barcode Placement: Using document.getElementById("barcode").innerHTML directly inserts the 36-character string into the intended span instead of writing to the top of the page with document.write().
  2. AUTH/TOKN String Generation: The showRandomNumber function now calls randomString with a character set containing digits and lowercase letters, producing the required 10-character alphanumeric strings.
  3. DOM Readiness: Wrapping the execution code in DOMContentLoaded ensures that all HTML elements are available before the JavaScript tries to modify them, preventing "element not found" errors.

内容的提问来源于stack exchange,提问作者Justin Reever

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 01:47:06