This question already has answers here:
Click event doesn't work on dynamically generated elements [duplicate]
                                
                                    (20个答案)
                                
                        
                                4年前关闭。
            
                    
onclick在后面的代码中创建一个按钮(Replybtn)。
--Default.aspx.cs--

protected void ReloadThePanelDetails_Click(object sender, EventArgs e)
{
  litResultDetails.Text = litResultDetails.Text +
  "<button id='Replybtn' onclick='replyfunc(this); return false;'>Reply to this thread</button><br />";
}


--Default.aspx--
单击使用JavaScript的Replybtn

 <script type = "text/javascript">
 function replyfunc(obj1) {
     document.getElementById(obj1.id).click();
  }
</script>


将jquery click事件用于Replybtn

<script>
$(document).ready(function () {
 $('.replypanel').css({ "display": "none" }); //div by default no display
    $("#Replybtn").click(function () {       //onclick div to display
        $('.replypanel').css({ "display": "block" });
    });
});
</script>


div不显示Replybtn的onclick(由后面的代码生成)。
请提出以上要求的任何其他解决方案或任何更新。

最佳答案

您需要使用Event delegation来侦听动态生成的dom元素

<script>
$(document).ready(function () {
 $('.replypanel').css({ "display": "none" }); //div by default no display
    $(document).on('click',"#Replybtn",function () {       //onclick div to display
        $('.replypanel').css({ "display": "block" });
    });
});
</script>

09-16 22:37