2013-11-27 85 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

好的我會盡我所能謝謝你,我一直在考慮改用javascript,但我非常習慣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

相關問題