-1

此代码采用 8 个 div 并根据 div 分配的时间值在屏幕上对它们进行竞赛。我怎样才能更好地编码这样我的代码看起来不那么业余?

我知道我应该在我的 for 循环中使用硬编码 8 以外的东西,但 timeArray.length 不可用,因为我正在使用拼接从数组中删除项目。

$(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);
});
});
4

1 回答 1

0

这确实是一个偏好和挑剔的问题,但既然你问了......

我听说on(...)大多数圈子都喜欢这种方法:

$('.pony').on('click', function() {

$('#startButton').on('click', function() {

当然,这取决于您使用的 jQuery 版本,并且可能完全是主观的。

于 2013-03-06T18:37:42.510 回答