Created
February 18, 2011 03:25
-
-
Save yuanchuan/833201 to your computer and use it in GitHub Desktop.
An interesting question
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head> | |
<meta charset="utf-8" /> | |
<title> An interesting question</title> | |
<style> | |
table { | |
border-collapse:collapse; | |
border-spacing:0; | |
margin: 100px auto 0; | |
} | |
p, td { | |
text-align:center; | |
} | |
td { | |
padding: 0 5px; | |
width:100px; | |
height:100px; | |
line-height:100px; | |
border:1px solid #bbb; | |
font-size:2em; | |
color:red; | |
} | |
#button { | |
padding: 15px 136px; | |
cursor:pointer; | |
font-weight:bold; | |
color:blue; | |
} | |
</style> | |
<script> | |
var Ring = (function() { | |
function Ring(list) { | |
this._list = [].slice.call(list, 0); | |
this._length = this._list.length; | |
this._curr = -1; | |
}; | |
Ring.prototype = { | |
rollTo: function(idx) { | |
this._curr = idx % this._length; | |
if (this._curr < 0) this._curr += this._length; | |
return this._list[this._curr]; | |
}, | |
next: function() { | |
return this.rollTo(this._curr + 1); | |
}, | |
prev: function() { | |
return this.rollTo(this._curr - 1); | |
} | |
}; | |
return function(list) { | |
return new Ring(list); | |
}; | |
}()); | |
window.onload = function() { | |
var numClicked = 0 | |
, cells = Ring( | |
document.getElementsByTagName('td') | |
); | |
document.getElementById('button') | |
.onclick = function() { | |
cells.next().innerHTML = (++numClicked); | |
} | |
} | |
</script> | |
</head> | |
<body> | |
<table> | |
<tbody> | |
<tr><td></td><td></td><td></td></tr> | |
<tr><td></td><td></td><td></td></tr> | |
<tr><td></td><td></td><td></td></tr> | |
</tbody> | |
</table> | |
<p><input id="button" type="button" value="Click me!"/></p> | |
</body> | |
</html> |
Finally, I made the code more explicit after a year.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've seen this somewhere...