简体   繁体   English

将单击按钮文本更改为随机选项

[英]Change button text on click to random option

I have around 12 different word that I want to be shown in random order when the user clicks a button.当用户单击按钮时,我希望以随机顺序显示大约 12 个不同的单词。 A new one every time they press the Button.每次他们按下按钮时都会有一个新的。 Is this possible to do with JS?这可能与JS有关吗? I've tried the method shown here: Random text on button click我已经尝试过这里显示的方法: Random text on button click

   Random myRandom = new Random();
   TextView textblondin = (TextView) findViewById(R.id.textblondin);
   switch(myRandom.nextInt() %3) {
      case 0:
         textblondin.setText("Text 1");
         break;
      case 1:
         textblondin.setText("Text 2");
         break;
      case 2:
     textblondin.setText("Text 3");
     break;
      default:
     break;
   }
}
}   

Would appreciate any help that points me in the right direction.将不胜感激任何帮助,指出我在正确的方向。 I'm new to Javascript.我是 Javascript 的新手。

Try this as your HTML:试试这个作为你的 HTML:

<button onclick="randomWord()">
 Random Word
</button>
<div id="word">
  Click to display a random word
</div>

And this as your JS:这作为你的 JS:

let randomWords = [ 'foo', 'bar' ];
let wordDiv = document.getElementById( 'word' );

function randomWord() {
    wordDiv.innerHTML = randomWords[ Math.floor(  Math.random() * randomWords.length ) ];
}

When you click the button it will find a random value from your array and set the div with ID "word" to this value.当您单击该按钮时,它将从您的数组中找到一个随机值,并将 ID 为“word”的 div 设置为该值。 You can change the values in the randomWords array to whatever you like.您可以将randomWords数组中的值更改为您喜欢的任何值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM