0

嗨,我正在尝试制作五个按钮,如您所见,我想要一个功能,当您按下“点击我”时,它将随机填充五个按钮。

这就像一个随机生成游戏的统计数据。

我不知道我是否做错了,但我认为我需要一些其他编码。

谁能帮助我?

这就是我所拥有的:

<button onclick='myFunction()'>click me</button>

<div id="demo">
<Input type = radio Name = r1> 
<Input type = radio Name = r2> 
<Input type = radio Name = r3> 
<Input type = radio Name = r4>
<Input type = radio Name = r5> 
</div>


<script type="text/javascript">

    function myFunction() {
    document.getElementById('demo').innerHTML = '';
    var num = 3;
    var noOfButtons = Math.floor(Math.random() * num);
    console.log(noOfButtons);
    for (var i = 0; i < noOfButtons; i++) {

    var box = document.createElement();
        document.getElementById('demo');
        }
    }
</script>
4

2 回答 2

1

不完全确定您在寻找什么。我把这个JSFiddle扔到了一起。看看它是否是你要找的。

<button id='button1'>click me</button>
<div id="demo">
    <input type='radio' id='r1'>
    <input type='radio' id='r2'>
    <input type='radio' id='r3'>
    <input type='radio' id='r4'>
    <input type='radio' id='r5'>
</div>

.

     var button1 = document.getElementById('button1');
     button1.onclick = function () {
         var noOfButtons = 5;
         var pick = Math.floor(Math.random() * noOfButtons) + 1;
         var radioBtn = document.getElementById('r' + pick);
         radioBtn.checked = true;
     }

[编辑]

于 2013-08-05T17:14:06.743 回答
0

I think what you're trying to do is randomly check a finite number of radios, in which case there's no need to set demo's html to ''. I added the class myRadios to the tags of your radios (just in case there are other radios on the page that you don't want to include in the random checking), and then used the following function:

function myFunction() {
    var radios = document.getElementsByClassName('myRadios');
    for (var i=0; i<radios.length; i++)
    {
        radios[i].checked = ( (Math.random()*10) > 5) ? true : false;
    }
}

Here is a a working fiddle. Let me know if this is the functionality you were looking for or if you have any questions about how it works :)

于 2013-08-05T19:25:55.347 回答