2012-05-20 38 views
0

基本上我创建了一个覆盖这装入appendTo为“加载屏幕”。添加可用按钮.AppendTo - Jquery的

最近,我需要添加一个停止按钮到覆盖这不是一个问题,但是jQuery的.click函数没有拿起按钮点击,我试着保留现有的按钮,因此它会也许注册,但可悲的是没有。

(我也使用的ID为按钮也试过

下面是一些测试代码来演示该问题

$(document).ready(function(){ 
    $("#addButton").click(function() { 
     $overlay = $("<div id='overlay'><div id='contain'><h3 style='color:#FFF'>Processing, just a moment</h3> <div id='stop'><button type='button' class='btn btn-primary' id='stop1' >Stop</button></div><div class='bar' style='width: 80%; padding-top:50%'></div></div></div"); 
     $overlay.appendTo(document.body); 
     $("#stop").click(function() { 
      alert("working"); 
     }); 
    }); 

编辑:。

只是为了澄清,这就是我本来想的,但是由于“过度变化”上面的例子将在我的情况下工作,这是最初的问题只是为了清楚起见。

$(document).ready(function(){ 
     $("#addButton").click(function() { 
      $overlay = $("<div id='overlay'><div id='contain'><h3 style='color:#FFF'>Processing, just a moment</h3> <div id='stop'><button type='button' class='btn btn-primary' id='stop1' >Stop</button></div><div class='bar' style='width: 80%; padding-top:50%'></div></div></div"); 
      $overlay.appendTo(document.body); 

     }); 

$("#stop").click(function() { 
       alert("working"); 
      }); 

}); 
+0

可能重复的[触发新添加的jQuery HTML代码(http://stackoverflow.com/questions/10677194/jquery-triggered-newly-added-html-code) – samjudson

+1

WORKSFORME:HTTP://的jsfiddle。 net/3HMcT/ – Bergi

+0

@samjudson:不,这是不同的。 '#stop'将在'$('#stop')之前的DOM中。click(...)'被调用以将处理程序绑定到它。 –

回答

1

是的,你也可以这样做。请参阅docs for the on() method

$(document).ready(function(){ 
    $("#addButton").click(function() { 
     $overlay = $("<div id='overlay'><div id='contain'><h3 style='color:#FFF'>Processing, just a moment</h3> <div id='stop'><button type='button' class='btn btn-primary' id='stop1' >Stop</button></div><div class='bar' style='width: 80%; padding-top:50%'></div></div></div"); 
     $overlay.appendTo(document.body); 
    }); 

    $(document).on("click", "#stop", function() { 
     alert("working"); 
    }); 
}); 

这仅增加了一个点击监听器文件,其中每触发一个click事件从#stop元素泡时间。但是,这通常只需要很多元素,所以当有多个这样的按钮时,最好使用“stop”类。

不过,我想你会需要你在执行权的onclick-行动的第一个例子不得不关闭。

1
$(document).ready(function(){ 
    $("#addButton").on('click', function() { 
     $overlay = $("<div id='overlay'><div id='contain'><h3 style='color:#FFF'>Processing, just a moment</h3> <div id='stop'><button type='button' class='btn btn-primary' id='stop1' >Stop</button></div><div class='bar' style='width: 80%; padding-top:50%'></div></div></div"); 
     $overlay.appendTo(document.body); 
    }); 

    $(document).on('click', '#stop', function() { 
     alert("working"); 
    }); 
}); 
+0

ü不要复制我的代码!我8秒更快:-) – Bergi

+0

@Bergi是的,我注意到了!不,我没有复制你的代码,只是写了几乎相同的东西? – adeneo

+0

我知道你不可能复制它,但我真的认为这将是完全一样的:-)刚开始认识的差异不大... +1的双重用途。对()的 – Bergi