我有一个笑话列表,我想在一个盒子里显示.当页面加载时,我想在框中随机显示一个.然后,当我单击该框时,我希望它再次将值更改为列表中的另一个随机值.
目前我无法让它工作,无法解决我出错的地方.我的HTML如下:
<input class="box" type="button" value"" />
<ul>
<li>How much do pirates pay to get their ear pierced? </br> A buck anear!</li>
<li>How do pirates talk to one another? </br> Aye to aye!</li>
<li>What did the sea say to the pirate captain? </br> Nothing, it justwaved!</li>
<li>What is a pirates favourite shop? </br> Ar-gos!</li>
<li>When is it the best time for a pirate to buy a ship? </br> Whenit is on sail!</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
该脚本是:
$(document).ready(function () {
var list = $("ul li").toArray();
var elemlength = list.length;
var randomnum = Math.floor(Math.random() * elemlength);
var randomitem = list[randomnum];
$('.box').click(function () {
$(this).val(randomitem);
});
});
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我如何在页面加载时使按钮具有值,然后在单击按钮时更改值.
那么你有两个问题.
首先是你总是选择相同的笑话(在页面加载时确定).第二个是你将整个li元素添加到按钮的值.
试试这个:
$(document).ready(function () {
var list = $("ul li").toArray();
var elemlength = list.length;
$('.box').click(function () {
// get a new joke every time a button is clicked
var randomnum = Math.floor(Math.random() * elemlength);
var randomitem = list[randomnum].innerHTML; // use the HTML of the <li>
$(this).val(randomitem);
});
});
Run Code Online (Sandbox Code Playgroud)