2013-11-27 4 views
1

개체 매개 변수의 모든 키를 입력으로하여 대화 상자를 만들려고합니다.클릭시 다른 함수가 호출되는 이유는 무엇입니까?

** Fiddle **

function dialog(opt){ 
    for (var key in opt) { 
     if (key=="msg" && typeof opt[key]==="string") 
      alert.append(opt[key]); //alert message 
     else if (typeof opt[key]==="function") { //alert functional button 
      console.log(key, "is a function"); 
      $("<input type=button>").val(key).appendTo(alert) 
       .on("click",function(){ console.log(key, 'called'); opt[key](); close(); }); 
     } else { //alert pretty button 
      console.log(key, "is not a function"); 
      //$("<input type=button>").val(key).appendTo(alert).click(close); 
     } 
    } 
} 
dialog({msg:"Yes or no?",yes:function(){},no:''}); 

나는 그것을 클릭하면하지만, '더는'함수로 호출되지 경우에만 '예'입력이 생성되는 : 당신이 공유하고 있기 때문에

yes is function   dialog.js:41 
no is not a function dialog.js:44 
no called    dialog.js:43 
Uncaught TypeError: Property 'no' of object #<Object> is not a function 
+0

에 추가 데이터 인수를 전달하여 각 이벤트에 데이터를 할당하고 일부를 잘라 수 있습니다 각 핸들러를 결합하는 것입니다 네이티브'typeof' 비교 연산자를 사용하여 jQuery의 오버 헤드. 예 :'if (typeof opt [key] === "function")'. 어쨌든 jQuery가 내부적으로하는 일일 것입니다. – War10ck

+0

ok 고맙다. 자바 스크립트로 바꾼다는 생각을 해왔다.하지만 jQuery에 익숙하다. – shuji

+1

이것이 폐쇄 문제라고 생각합니다 ... –

답변

1

그것은이다 key 모든 처리기 사이의 변수이며 그 값은 루프를 빠져 나간 후 값인 'no'입니다. 이 솔루션은 JQuery와 당신이 $.on

function dialog(opt){ 
    for (var key in opt) { 
     $("<input type=button value="+key+" style='margin:5% 3%;padding:3% 7%;'>"). 
     appendTo('#alert'). 
     on("click", {fn: opt[key]}, function(e){ 
      // Whatever you bound to the argument is stored in e.data 
      if (typeof e.data.fn ==="function") { 
       e.data.fn(); 
      } else { 
       alert('You passed in "' + e.data.fn + '"'); 
      } 
     }); 
    } 
} 
dialog({ 
    msg:'Whatever', 
    yes:function(){ 
     alert('clicked yes') 
    }, 
    no:'' 
}); 
나는 그것이 차이를 만들 것입니다 생각하지 않는 것이

http://jsfiddle.net/mendesjuan/8JChZ/3/

+0

고맙습니다. 어떻게 해결해야할지 모르겠습니다. – shuji

관련 문제