与事件绑定功能动态插入的DOM节点
问题描述:
首先计算器问题,所以,请温柔:)与事件绑定功能动态插入的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元素?不必硬编码选择器?
答
由于事件委托,jQuery解决了这个问题。尝试.delegate()方法。
即使在构建表的DOM之前,也可以使用$('div.prompt').delegate('td', 'click', function(){ ... })
。它将自动为以后添加的元素工作。