자바스크립트, for문에 대해서 간단한 질문

java200의 이미지

간단한 문장인데 for문으로 바꾸기가 참 애매하네요
조언 좀 구합니다

<script type="text/javascript">

btn1=document.getElementById('btn1')
btn2=document.getElementById('btn2')
btn3=document.getElementById('btn3')

btn1.onclick=function(){
alert("1");
}

btn2.onclick=function(){
alert("2");
}

btn3.onclick=function(){
alert("3");
}

</script>

익명 사용자의 이미지

for (i = 1; i <= 3; i ++) {
var btn = document.getElementById("btn" + i);
btn.onclick = function() {
alert(i);
}
}

이런식으로 하면 되지 않을까요?

익명 사용자의 이미지

이건 반복문 다 돌고난뒤에 4만 출력될 겁니다. 기본적인 프로그래밍 지식을 배우셔야 할듯....

익명 사용자의 이미지

님은 말투부터 배우셔야할듯

익명 사용자의 이미지

for (i = 1; i <= 3; i++)
    (function (i) {
        var btn = document.getElementById('btn' + i);
        btn.onclick = function () {
            alert(i);
        }
    })(i);
woonuk의 이미지

안그래도 궁금해서 이리저리 검색하고 테스트 해봐도 안되어서 답답했었는데,

덕분에 뻥 뚫렸습니다.

스크랩용 덧글 ^^;

java200의 이미지

근데 (function (i)) (i);<- 여기가 좀 생소한데
자바스크립트에 이런 문법도 있었나요

klara의 이미지

자바스크립트에서는 함수가 first-class object입니다.

var f = function(i) {...};
f(i);

와 같습니다.

neocoin의 이미지

var f = function(i){ alert('hello world');}
f();

=>

(function(i){ alert('hello world');})();

라고 생각하면 됩니다.

HDNua의 이미지

+1

저는 이렇게 생각했습니다.

익명 사용자의 이미지

자바스크립트에서 함수는 1종 객체입니다.
그러니까 배열, 객체, String 보다 함수 우선합니다.
그 근거로 익명함수를 들 수 있습니다. function (){}
익명 함수 말 그대로 네임스페이스가 없는 선언된 이름이 없는 함수 입니다.
이것은 자바스크립트의 특성이고 이 익명함수는 객체처럼 인자로 전달되거나 반환되기도 합니다.
이를 두고 자바스크립를 '함수형 언어'라고 부릅니다.
위에서 말씀하신 (function (){})(); 은 즉시실행함수라고 합니다.
익명함수를 묵고 있는 앞의 괄호는 우리가 연산을 하는데 쓰이는 (a + b) 와 같은 기능입니다.
뒤의 괄호는 앞의 괄호를 실행하는 것이지요. 즉 함수 실행입니다.
함수 실행시 인자를 전달할 수 있습니다.
그렇다면 즉시실행함수도 인자를 전달할 수 있고 함수는 매개변수로 그 인자를 전달받겠죠...
그래서 i 는 연결됩니다. 그리고 바로 실행됩니다.
(function (i) {

})(i);
즉시실행함수를 쓰는 이유는 클로저의 개념과 연결되어 있기에 부가적으로 길잡이가 되어줄 교재로 공부하심이 좋겠네요.
jQuery 코드나 자바스크립트 라이브러리 코드등을 보면 흔히 사용하는 방식입니다.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.