2011-02-15 68 views
0

首先計算器問題,所以,請溫柔:)與事件綁定功能動態插入的DOM節點

林做了鍍鉻web應用完全由javascript和我想自己儘可能更多鈔票編碼。因此,我必須在未保存的文檔上提供一些功能,例如系統提示/警告。

爲了使這提示功能的便攜式儘可能邏輯是這樣:

function prompt (String message, assocArray commandname:function) 
Print message 
for each command 
make button and .bind click(function) to it 

顯然即時使用jQuery此。

問題是,如何將單擊事件上的函數綁定到未插入的Dom元素,而無需對選擇器進行硬編碼以及儘可能少的代碼行?

下一個代碼是錯誤的,但它代表我想要做的事情。

var message = "Document is not saved, do you want to save it now?"; 

    var options = { 
     "yes": function(){alert("yes")}, 
     "no": function(){alert("no")}, 
     "cancel": function(){alert("cancel")} 
    } 

    systemPrompt = function(message, options){ 
     $("body").append("<div class='prompt'><div class='prompt_message'><p>"+message+"</p><div class='options'></div></div></div"); 
     var optionsContainer = $('.promt_mesage .options').append("<table><tr></tr></table>"); 
     for(command in options){ 
      optionContainer.append("<td>"+command+"</td>").bind('click', function(){ 
       options[command]; 
      }); 
     } 
    }; 

與此相關的問題:如何抓住一個新插入的dom元素?不必硬編碼選擇器?

回答

0

由於事件委託,jQuery解決了這個問題。嘗試.delegate()方法。

即使在構建表的DOM之前,也可以使用$('div.prompt').delegate('td', 'click', function(){ ... })。它將自動爲以後添加的元素工作。