我怎样才能更好地编写代码,使我的代码看起来不那么业余呢?
How can I have coded this better so my code doesn't look so amateurish?
这段代码获取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);
});
});
这确实是一个偏好和挑剔的问题,但既然你问了…
我听说on(...)
方法在大多数圈子中是首选的:
$('.pony').on('click', function() {
和
$('#startButton').on('click', function() {
当然,这取决于你使用的是什么版本的jQuery,可能完全是主观的
相关文章:
- Steam Web API:I'我不知道该如何处理这个看起来像哈希的url来生成图像
- 如何使删除线看起来像x
- Twitter Bootstrap 2.1.0子菜单在Responsive上看起来很混乱
- 用javascript创建一个看起来正常分布的模式
- PHP函数的返回看起来如何对AJAX和PHP有效
- 如何使Codeschools棱角分明的一面看起来相似
- HTML/JavaScript拖动&Drop-是否可以使重影图像*NOT*看起来'冲洗掉'
- 未捕获的语法错误:意外的令牌非法?看起来不错
- NodeJS readline有时会打印回第一个输入行(但并不总是,看起来是随机的)
- 如何检查html是否看起来'空'
- 相同的css和HTML代码,但在两页上看起来不同
- 钛-圆形表视图看起来不像代码
- 代码优化,如何使其看起来不错
- 是否可以包含许多.js文件以使我的代码看起来模块化
- 对于循环&if.else语句..我的代码看起来怎么样
- MSIE让我的slidejs代码看起来很糟糕
- jQuery代码看起来效率低下,你能帮忙吗?替换导航中的文本
- PHP MVC应该看起来像jQuery/javascript代码
- 在我将其与$("#id")一起使用后,相同的代码就不起作用了.append.代码看起来像没有加载jq
- 我怎样才能更好地编写代码,使我的代码看起来不那么业余呢?