从两个点中的数组显示随机字

时间:2015-03-15 05:36:10

标签: javascript arrays button random

<input type="button" id="btnSearch" value="Search" onclick="myFunction();" />
<div id="message">
    <p></p>
</div>
<br>
<div id="message">
    <p></p>
</div>


<script type="text/javascript">
    function myFunction() {
        var myarray= new Array ("Drama", "Fable", "Fairy Tale", "Fantasy", "Fiction", "Folklore", "Historical Fiction", "Horror", "Humor", "Mystery", "Mythology", "Poetry", "Realistic Fiction", "Science Fiction", "Short Story", "Tall Tale");

        var random = myarray[Math.round(Math.random() * (myarray.length - 1))]

        var display = document.getElementById("message").innerHTML=random;
    }
</script>

到目前为止,我有这个,我想要做的是点击一下按钮,从我的阵列中相互旁边显示两个随机单词。在此先感谢您的帮助!

https://jsfiddle.net/edexxmjo/

2 个答案:

答案 0 :(得分:0)

id是唯一的,如果您需要在两个位置显示,请使用class选择器或添加另一个唯一的id,如下所示,

<div id="message">     
</div>
<br>
<div id="message_2">      
</div>

<script type="text/javascript">
    function myFunction() {
    var myarray= new Array ("Drama", "Fable", "Fairy Tale", "Fantasy", "Fiction", "Folklore", "Historical Fiction", "Horror", "Humor", "Mystery", "Mythology", "Poetry", "Realistic Fiction", "Science Fiction", "Short Story", "Tall Tale");

    var random = myarray[Math.round(Math.random() * (myarray.length - 1))]

    document.getElementById("message").innerHTML=random;
    document.getElementById("message_2").innerHTML=random;
    }
</script>

To Get Elements by ID, Tag, Name, Class, CSS Selector

答案 1 :(得分:0)

也许这是一个可能的解决方案

<button type="button" id="myBtn">Search</button>
<div id="message1">
</div>
<br>
<div id="message2">
</div>

这是javascript

document.getElementById("myBtn").addEventListener("click", clickHandler);

function clickHandler(event) {
    event.preventDefault();
    document.getElementById("message1").innerHTML = selectedWord();
    document.getElementById("message2").innerHTML = selectedWord();
}

function selectedWord(){
    var myarray = new Array("Drama", "Fable", "Fairy Tale", "Fantasy", "Fiction", "Folklore", "Historical Fiction", "Horror", "Humor", "Mystery", "Mythology", "Poetry", "Realistic Fiction", "Science Fiction", "Short Story", "Tall Tale");

    return myarray[Math.round(Math.random() * (myarray.length - 1))];
}