在Reload上的HTML输入中显示随机文本

时间:2018-04-28 12:00:19

标签: javascript html

我现在是一名新手编码员,所以我需要一些帮助。

我想在页面加载/重新加载时在html字段中显示随机字符串文本。我希望从我的列表中选择一个随机的文本字符串。

哦,顺便说一下,我可以有一个JsFiddle链接(如果可能的话)

〜谢谢,Calo

3 个答案:

答案 0 :(得分:1)

每次重新加载时都会显示随机数。



// find elements
var banner = $("#banner-message-text")
banner.val(parseInt(Math.random()*18546876546));

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="banner-message">
  <input type="text" id="banner-message-text"/>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

let messages = ["Hi", "Hey", "Hello", "Please make some attempts", "holla"];
 // We can use inbuilt Math object to perform mathematical operations.
 // to get a random number between 0 and the total size of messages array, we can use it as follows. 
 // Math.floor will return the largest integer which is less than or equal to that random number.
    let message = messages[Math.floor(Math.random()*messages.length)];

// to select your input element and set default value, you can do
$('input').val(message);

参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math

答案 2 :(得分:1)

这应该这样做。您可以简单地将更多句子添加到包含样本的数组中。

var texts = [
  "I am a sentence.",
  "Some nice stuff.",
  "I am random too!"
];

document.getElementById('randomText').value = texts[Math.floor(Math.random()*texts.length)];
<input type="text" id="randomText">