我希望每次点击
时都会触发我的jquery
$(function(){
var list = $("ul li").toArray();
var elemlength = list.length;
var randomnum = Math.floor(Math.random()*elemlength);
var randomitem = list[randomnum];
$("#button").bind('click', function(e){
$(randomitem).addClass("lunch");
});
});
答案 0 :(得分:1)
您需要在点击处理程序中找到随机项
$(function () {
$("#button").bind('click', function (e) {
var list = $("ul li:not(.lunch)");
$("ul li.lunch").removeClass('lunch')
var elemlength = list.length;
var randomnum = Math.floor(Math.random() * elemlength);
list.eq(randomnum).addClass("lunch");
});
});
演示:Fiddle
答案 1 :(得分:0)
首先:
randomnum
和randomitem
的范围错误。休息应该有助于:)
示例代码
$(function () {
var list = $("ul li").toArray();
var elemlength = list.length;
$("#button").on('click', function (e) {
var randomnum = Math.floor(Math.random() * elemlength);
var randomitem = list[randomnum];
$(randomitem).addClass("lunch");
});
});