【问题标题】:How can I put text before a random number in a <p>?如何在 <p> 中将文本放在随机数之前?
【发布时间】:2020-05-21 20:16:14
【问题描述】:

我正在尝试在文本中插入一个Math.random(),这样它就会说“你的号码是”,然后是来自Math.random() 的号码。我可以从这行代码中看到它是可能的:alert("Copied the text: " + copyText.value);。它向您显示了您复制的内容,但我似乎无法弄清楚如何使用 Math.random() 来做到这一点。

function myFunction() {
  var x = document.getElementById("demo")
  x.innerHTML = Math.floor((Math.random() * 89999) + 10000);
}
<!DOCTYPE html>
<html>

<body>

  <p>Click the button to display a random 5 digit number.</p>

  <button onclick="myFunction()">Try it</button>

  <p id="demo"></p>

  <p>I want it to say something before the number like 'order #' and then the random number</p>
</body>

</html>

【问题讨论】:

标签: javascript html string concatenation


【解决方案1】:

而不是使用

x.innerHTML = Math.floor((Math.random() * 89999) + 10000);

使用template string,像这样:

function myFunction() {
  var x = document.getElementById("demo")
  x.innerHTML = `You generated ${Math.floor((Math.random() * 89999) + 10000)}`;
}
<!DOCTYPE html>
<html>

<body>

  <p>Click the button to display a random 5 digit number.</p>

  <button onclick="myFunction()">Try it</button>

  <p id="demo"></p>
</body>

</html>

模板字符串让您可以轻松地组合字符串和 JS 代码。您可以像将普通字符串一样将文本放入模板字符串中。您还可以通过将 JavaScript 代码包含在 ${...} 中来放置将被评估、转换为字符串并放置在模板字符串中的 JavaScript 代码。模板字符串非常强大,可以用来做比我上面展示的简单示例更多的事情。我建议您阅读我上面链接的有关它们的文档。

或者,您可以使用 + 运算符连接字符串。这是一个例子

x.innerHTML = "You generated " + Math.floor((Math.random() * 89999) + 10000).toString();

两者具有相同的效果,但模板字符串更强大,并且尽可能是最佳实践。

【讨论】:

  • 哇,非常感谢!我什至没有考虑过模板字符串,但效果很好。
  • 如果答案对您有用,您应该点击复选标记接受它。这表明答案是正确的并回答了您的问题。通过接受答案,您可以帮助发现问题的其他人也更好地了解如何解决他们的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-21
相关资源
最近更新 更多