[英]How can I put text before a random number in a <p>?
I'm trying to insert a Math.random()
into text so it would say "your number is" and then the number from the Math.random()
.我正在尝试将Math.random()
插入到文本中,这样它会说“你的号码是”,然后是来自Math.random()
的号码。 I can see that it I possible from this line of code: alert("Copied the text: " + copyText.value);
我可以从这行代码中看到我有可能: alert("Copied the text: " + copyText.value);
. . It shows you what you've copied but I cannot seem to figure out how to do that with Math.random()
.它向您展示了您复制的内容,但我似乎无法弄清楚如何使用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>
Instead of using而不是使用
x.innerHTML = Math.floor((Math.random() * 89999) + 10000);
Use a template string , like so:使用模板字符串,如下所示:
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>
Template strings allow you to easily combine strings and JS code.模板字符串允许您轻松地组合字符串和 JS 代码。 You can put text in the template string as you would a normal string.您可以像将普通字符串一样将文本放入模板字符串中。 You can also put JavaScript code that will be evaluated, converted to a string, and placed in the template string by enclosing it in ${...}
.您还可以将 JavaScript 代码放入将被评估、转换为字符串并通过将其包含在${...}
中的模板字符串中。 Template strings are ver powerful and can be used to do much more than the simple example I showed above.模板字符串非常强大,可以用来做比我上面展示的简单示例更多的事情。 I suggest you read the documentation about them I linked above.我建议您阅读我上面链接的有关它们的文档。
Alternatively, you could just concatenate strings by using the + operator.或者,您可以使用 + 运算符连接字符串。 Here's an example这是一个例子
x.innerHTML = "You generated " + Math.floor((Math.random() * 89999) + 10000).toString();
Both have the same effect, but template strings are more powerful and are a best practice whenever possible.两者具有相同的效果,但模板字符串更强大,并且尽可能是最佳实践。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.