我正在尝试创建一个网站,您可以在其中输入您的姓名,然后按"计算"然后它将随机带有该名称,并将其附加到一个方框中。这是我的HTML:
<form class="newName">
<label for="nameInput">Your Name</label>
<input class="input-md" id="nameInput" placeholder="(e.g: John Smith)">
<span class="btn-names">Enter...</span>
<span class="calculate">Calculate</span>
</form>
<div class="namesEntered">
<ul id="enteredNames"></ul>
</div>
<div class="centered">
<h1>And The Winner Is....</h1><br><br>
<span id="name" class="names">???</span>
</div>
我的JavaScript / jQuery:
$(document).ready(function(){
$('.btn-names').on('click', function(){
if ($('#nameInput').val() === ''){
alert('No names have been entered');
} else {
var $inputted_names = $('#nameInput').val();
var listed = '<li>'+ $inputted_names +'</li>';
$(listed).appendTo('ul');
$('#nameInput').val('');
}
});
$('.calculate').on('click', function(){
var tag = document.getElementsByTagName('li');
var name = tag.innerHTML;
var randomator = Math.floor(Math.random(tag) * name.length);
console.log(randomator);
});
});
您可以在http://www.b3ws.com/randomator.html查看此示例网站 但它还没有发挥作用
答案 0 :(得分:1)
首先,获取一个li
元素数组,如
var names = $('#enteredNames li');
然后,获取随机名称
var randomName = names.get(Math.floor(Math.random()*names.length));
最后,更改#name
范围
$('#name').text(randomName.innerHTML);
$(document).ready(function(){
$('.btn-names').on('click', function(){
if ($('#nameInput').val() === ''){
alert('No names have been entered');
} else {
var $inputted_names = $('#nameInput').val();
var listed = '<li>'+ $inputted_names +'</li>';
$(listed).appendTo('ul');
$('#nameInput').val('');
}
});
$('.calculate').on('click', function(){
var names = $('#enteredNames li');
var randomName = names.get(Math.floor(Math.random()*names.length));
$('#name').text(randomName.innerHTML);
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<label for="nameInput">Your Name</label>
<input class="input-md" id="nameInput" placeholder="(e.g: John Smith)">
<span class="btn-names">Enter...</span>
<span class="calculate">Calculate</span>
<div class="namesEntered">
<ul id="enteredNames"></ul>
</div>
<div class="centered">
<h1>And The Winner Is....</h1><br><br>
<span id="name" class="names">???</span>
</div>
&#13;
答案 1 :(得分:0)
Replace your randomator section with this:
var randomator = Math.floor(Math.random() * tag.length); //don't need tag in random function
console.log(randomator);
$('.names').html(tag[randomator].text()); //assign the test from the random tag to the element with the names class