[英]Click event doesn't work after append
I want to dynamic click on first click of paragraph but its not working. 我想动态点击段落的第一个点击,但它不起作用。
$(document).ready(function() { $(".newclass").click(function() { var append_code = '<a href="google.com" class="hrefclick">Youre clicked</a>'; $('body').append(append_code); $(".hrefclick").click(); $(document).on('click', '.hrefclick', function(e) { alert("yess! You're clicked"); // do whatever }); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p class="newclass"> Hit me! </p>
You need to trigger the click()
after the delegation, just change the order of your lines: 您需要在委派后触发
click()
,只需更改行的顺序即可:
$(document).ready(function() { $(".newclass").click(function() { var append_code = '<a href="google.com" class="hrefclick">Youre clicked</a>'; $('body').append(append_code); $(document).on('click', '.hrefclick', function(e) { alert("yess! You're clicked"); // do whatever }); $(".hrefclick").click(); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p class="newclass"> Hit me! </p>
$(document).ready(function() { $(".newclass").click(function() { var append_code = '<a href="google.com" class="hrefclick">Youre clicked</a>'; $('body').append(append_code); $(".hrefclick").click(); $(document).on('click', '.hrefclick', function(e) { alert("yess! You're clicked"); // do whatever }); $('.hrefclick').trigger('click'); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p class="newclass"> Hit me! </p>
You are doing everything correct except one thing - You are declaring event handler of your second click after the click itself. 您所做的一切都正确,除了一件事情-您在单击本身之后声明第二次单击的事件处理程序。 So, when second click is triggered, you don't have handler declared yet and you don't see any alert.
因此,触发第二次单击时,您尚未声明处理程序,也看不到任何警报。 I rearranged it below.
我在下面重新排列了它。 Trying running the below snippet.
尝试运行以下代码段。
$(document).ready(function() { $(".newclass").click(function() { var append_code = '<a href="google.com" class="hrefclick">Youre clicked</a>'; $('body').append(append_code); //on click event handler should be declared first before clicking $(document).on('click', '.hrefclick', function(e) { alert("yess! You're clicked"); // do whatever }); $(".hrefclick").click(); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p class="newclass"> Hit me! </p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.