为动态生成的按钮添加按钮处理程序

时间:2015-07-24 02:27:25

标签: javascript events

我有以下javascript代码:

$(document).ready (function()
{ 
    setInterval("RepeatedlyCallUpdate()",10000);
    // Other code
    $('#btnRefresh').click(function(e){
        e.preventDefault();
        alert ("Test");
    }); 
    // Other code

}); 

function RepeatedlyCallUpdate() { 
  $.ajax({
   url: "/getdled.php",
   data: "user=success",
   success: function(msg){
     console.log(msg);
     var oldhtml=$("#Downloaded").html();
     if ( msg !== oldhtml ) {
        $("#Downloaded").html(msg);
     }       

   }
 });
}

#Downloaded的html代码:

<div id="Downloaded"><h3 style="padding-left:20px;">Downloaded files</h3>
</div>

在运行时,使用html代码填充#Downloaded div块,使其成为:

<div id="Downloaded"><h3 style="padding-left:20px;">Downloaded files</h3>
<ul class="nav nav-pills">
<li>
<button style="margin-left: 15px;" class="btn btn-primary refreshbtn" type="button" id="btnRefresh">
Refresh
</button>
</li>
</ul><div>
<div class="row">
    <div style="margin-left: 15px;" class="col-md-4">
    <a href="somthing">Some link</a></div>
    <div class="col-md-1">314M</div>
    </div>
</div>
</div>

问题是我的#Downloaded按钮点击事件不会触发。我错过了什么?

1 个答案:

答案 0 :(得分:0)

您可以使用事件委派

$("#Downloaded").on('click', '#btnRefresh', function(){
    alert("lol");
});