第一个堆栈溢出问题,所以要温和:)
我正在制作一个完全由javascript组成的chrome webapp,我想自己编写尽可能多的代码。因此,我必须做一些功能,如系统提示/警告未保存的文件。
为了使提示符功能尽可能可移植,逻辑是这样的:
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元素?而不必对选择器进行硬编码?
发布于 2011-02-15 18:37:28
多亏了事件委托,jQuery解决了这个问题。尝试.delegate()方法。
甚至在构建表的DOM之前就可以使用$('div.prompt').delegate('td', 'click', function(){ ... })
。它将自动为稍后添加的元素工作。
https://stackoverflow.com/questions/5007834
复制