작성일 : 16-08-11 04:00
|
[JQuery] jquery for
|
|
|
글쓴이 :
조형래
 조회 : 2,562
|
안녕하세요. 간단할수도 있는 jquery for문 질문드립니다.
아래와 같은 소스가 있습니다.
html 부분
<button id=button1>버튼1</button>
<button id=button2>버튼2</button>
<button id=button3>버튼3</button>
jquery 부분
<script>
$(function(){
for(var i=1; i <= 3; i++){
$("#button"+i).click(function(){
alert(i);
});
}
});
</script>
제가 원하는 현상은 button1을 누르면 1이 출력되고,
button2를 누르면 2가 출력되고 button3을 누르면 3이 출력되야하는데,
버튼 어느것을 눌러도 뜬금없는 4가 출력이 되네요...
jquery의 for문이 다른개념인건가... 좋은 답변 기다리겠습니다 ㅠ
function 안에 function 의 변수 공유하려면 아래처럼 하셔야 합니다.
<script src="jquery.js"></script>
<script>
$(function(){
for(var i=1; i <= 3; i++){
(function() {
var i2 = i;
$("#button"+i2).click(function(){
alert(i2);
});
})();
}
});
</script>
|
|