我正在尝试让 JavaScript 从文本区域中随机选择一行。抱歉,这里是大菜鸟。
目前我的代码看起来像这样,我很确定其中存在愚蠢的错误。我只是有点卡住了。首先,如何将此函数连接到文本区域?其次,我如何输出结果? 我认为我在使其成为两个功能方面做得太多了。我不介意以某种方式让它变小。
<body>
<div class="container">
<h3>
Enter all of the names on a seperate line. <br />
</h3>
<textarea id="textarea" placeholder="Enter names here..."></textarea>
</div>
<h3>The winner is: <span id = "winner"></span></h3>
<button onclick="randomSelect()">Click me</button>
<script>
function randomSelect() {
const lines = input.split('\n');
const randomLine = lines[Math.floor(Math.random() * lines.length))];
selectOutput();}
}
function selectOutput() {
document.getElementById("winner").innerHTML = ;
}
</script>
</body>
</html>
您的代码应如下所示:
<body>
<div class="container">
<h3>
Enter all of the names on a seperate line.
</h3>
<label for="textarea">Enter names: </label><br />
<textarea id="textarea" placeholder="Enter names here..."></textarea>
</div>
<h3>The winner is: <span id = "winner"></span></h3>
<button onclick="randomSelect()">Click me</button>
<script>
function randomSelect() {
const input = document.getElementById('textarea').value;
const lines = input.split('\n');
const randomLine = lines[Math.floor(Math.random() * lines.length)];
//Display your line
document.getElementById('winner').innerHTML = randomLine;
}
</script>
</body>
您只是忘记识别从中获取值的元素。 但你做得很好。
function randomSelect() {
const winnerEl = document.getElementById("winner");
winnerEl.innerHTML = "";
const candidates = document.getElementById("textarea").value;
if (candidates) {
const names = candidates.split(/\n/);
if (names.length > 0) {
const max = names.length - 1;
const winnerIndex = getRandomInt(0, max);
winnerEl.innerHTML = names[winnerIndex];
}
}
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
<body>
<div class="container">
<h3>
Enter all of the names on a seperate line. <br />
</h3>
<textarea id="textarea" placeholder="Enter names here..."></textarea>
</div>
<h3>The winner is: <span id = "winner"></span></h3>
<button onclick="randomSelect()">Click me</button>
</body>
</html>
在您的
randomSelect()
函数中访问您的文本区域和存储在其中的值。
因此添加以下行
const input = document.getElementById("textarea").value;