此代码需要8个div并在屏幕上对它们进行比赛,具体取决于div的分配时间值。我怎样才能更好地编码,以便我的代码看起来不那么业余?
我知道我应该在我的for循环中使用除硬编码8以外的东西,但是timeArray.length不可用,因为我正在使用splice从数组中删除项目。
$(document).ready(function() {
var timeArray = new Array(3,4,5,6,7,8,9,10);
var shortestTime = timeArray[7];
var fastestPony = {};
var index;
var pony = {
name: "pony",
raceTime: -1,
selected: ""
};
//change the color of the pony when the user clicks on it
$('.pony').bind('click', function() {
$('.pony').removeClass('selectedPony');
$(this).addClass('selectedPony');
//get the pony that the user selected
pony.selected = $(this);
});
$('#startButton').click(function() {
if (pony.selected == "") {
alert("Please click the pony you think will win the race.");
}
else {
for (i = 1; i <= 8; i++) {
//get a random number from the timeArray
index = Math.floor(Math.random() * timeArray.length);
pony.raceTime = timeArray[index];
//pull the random race time number out of the array
//so it can't be assigned to another horse
timeArray.splice(index, 1);
//get the fastest pony
if (pony.raceTime < shortestTime) {
shortestTime = pony.raceTime;
fastestPony = $('#pony' + i);
}
//award the winner after the ponies have reached the finish line
if (i == 8) {
fastestPony.addClass('winner').append(' - Winner!');
}
//send the horses on their way to race!
$('#pony' + i).animate({left: '320px'}, pony.raceTime * 1000);
}
}
});
//reset the ponies back to the starting line by reloading the page
$('#resetButton').click(function() {
document.location.reload(true);
});
});
答案 0 :(得分:0)
这真的是一个偏好和挑剔的问题,但是因为你问过......
我听说大多数圈子都首选on(...)
方法:
$('.pony').on('click', function() {
和
$('#startButton').on('click', function() {
当然这取决于您使用的jQuery版本,可能完全是主观的。