Skip to content

Instantly share code, notes, and snippets.

@tomoTaka01
Created April 13, 2014 05:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomoTaka01/10570241 to your computer and use it in GitHub Desktop.
Save tomoTaka01/10570241 to your computer and use it in GitHub Desktop.
Simple closure sample.
<!DOCTYPE html>
<html>
<head>
<title>Adder Sample(java script)</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="js/libs/jquery/jquery.js" ></script>
<script>
$(function() {
$('#result').text('0');
adder = function(addVal){
var i = 0; // <-- 変数「i」は、add1、add2のボタン毎に保持
return function() {
i += addVal;
$('#result').text(i);
};
};
$('#add1Button').click(adder(1));
$('#add2Button').click(adder(2));
$('#addDiv').click(function(event){
var tmp = $('#history').text();
$('#history').text(tmp + event.target.id + "\n");
});
});
</script>
</head>
<body>
<div style="font-size: 16px; color:blue">Adder Sample(java script)</div>
<div>
<label>value:</label>
<output id="result" style="color: red; font-weight: bold"></output>
</div>
<div id="addDiv">
<input type="button" id="add1Button" value="add1" />
<input type="button" id="add2Button" value="add2" />
</div>
<div style="margin-top: 10px">
<label>click history</label>
<br/>
<textarea id="history" style="height: 100px;"></textarea>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment