javascript 从文本区域中随机选取一行

javascript pick random line from a textarea

我正在尝试让 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>

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>

您的代码应如下所示:

<html>
<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="randonSelect()">Click me</button>

<script>
 function randonSelect() {
    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>
</html>

您只是忘记获取要从中获取值的元素。 但是你做得很好

在您的 randomSelect() 函数中访问您的文本区域和存储在其中的值。 因此添加以下行

    const input = document.getElementById("textarea").value;