我正在尝试创建一个 HEX 代码生成器并将其显示在标题上,但问题是它不会覆盖标题内的文本,而是仅将其放置在标题旁边。

let hexGenerator = {
	result: '',
	characters: 'ABCDEF0123456789',
	hexColor: function() {
		for (let i = 0; i < 6; i++) {
			this.result += this.characters.charAt(Math.floor(Math.random() * this.characters.length));
		}
		return this.result;
	}
}

window.onload = () => {
	document.querySelector('button').addEventListener('click', () => {
		document.getElementById('demo').innerHTML = 'HEX VALUE: #' + hexGenerator.hexColor();
	})
}
<body>
  <h1 id="demo">HEX VALUE: #</h1>
  <button>Click Me!</button>
</body>

最佳答案

element.innerHTML = ... 确实会覆盖。
result += ... 不会覆盖。

感谢您提供最低限度的示例。添加 this.result = '' 将重置每次点击的值。

let hexGenerator = {
  result: '',
  characters: 'ABCDEF0123456789',
  hexColor: function() {
    this.result = '';
    for (let i = 0; i < 6; i++) {
      this.result += this.characters.charAt(Math.floor(Math.random() * this.characters.length));
    }
    return this.result;
  }
}

window.onload = () => {
  document.querySelector('button').addEventListener('click', () => {
    document.getElementById('demo').innerHTML = 'HEX VALUE: #' + hexGenerator.hexColor();
  })
}
<body>
  <h1 id="demo">HEX VALUE: #</h1>
  <button>Click Me!</button>
</body>


话虽如此,没有理由在这里创建一个 hexGenerator 对象。你可以只使用一个简单的函数:

let hexColor = () => {
  let characters = 'ABCDEF0123456789';
  let result = '';
  for (let i = 0; i < 6; i++)
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  return result;
};

window.addEventListener('load', () =>
  document.querySelector('button').addEventListener('click', () =>
    document.getElementById('demo').textContent = 'HEX VALUE: #' + hexColor()));
<body>
  <h1 id="demo">HEX VALUE: #</h1>
  <button>Click Me!</button>
</body>


编辑::每条评论,这是您使用 classes 执行此操作的方法:

class Generator {
  constructor() {
    this.characters = 'ABCDEF0123456789';
  }

  hexColor() {
    let result = '';
    for (let i = 0; i < 6; i++)
      result += this.characters.charAt(Math.floor(Math.random() * this.characters.length));
    return result;
  }
}

let gen = new Generator();

window.addEventListener('load', () =>
    document.querySelector('button').addEventListener('click', () =>
      document.getElementById('demo').textContent = 'HEX VALUE: #' + gen.hexColor()));
<body>
  <h1 id="demo">HEX VALUE: #</h1>
  <button>Click Me!</button>
</body>

关于javascript - innerHTML 不会覆盖,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61104070/

10-11 20:25