Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用事件绑定函数动态插入dom节点_Javascript_Jquery_Events_Dom - Fatal编程技术网

Javascript 使用事件绑定函数动态插入dom节点

Javascript 使用事件绑定函数动态插入dom节点,javascript,jquery,events,dom,Javascript,Jquery,Events,Dom,第一个问题,所以要温柔:) 我正在制作一个完全由javascript组成的chrome网络应用程序,我想自己编写尽可能多的代码。因此,我必须对未保存的文档执行一些功能,如系统提示/警告 为了使该提示功能尽可能可移植,逻辑如下: function prompt (String message, assocArray commandname:function) Print message for each command make button and .bind click(funct

第一个问题,所以要温柔:)

我正在制作一个完全由javascript组成的chrome网络应用程序,我想自己编写尽可能多的代码。因此,我必须对未保存的文档执行一些功能,如系统提示/警告

为了使该提示功能尽可能可移植,逻辑如下:

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];
            });
        }
    };
var message=“文档未保存,是否立即保存?”;
变量选项={
“是”:函数(){alert(“yes”)},
“否”:函数(){alert(“no”)},
“取消”:函数(){alert(“cancel”)}
}
systemPrompt=功能(消息、选项){

$(“body”).append(“”+message+”

jQuery通过事件委派解决了此问题。请尝试此方法

即使在构建表的DOM之前,也可以使用
$('div.prompt').delegate('td','click',function(){…})
。它将自动为以后添加的元素工作