[英]Click event doesn't work after append
我想动态点击段落的第一个点击,但它不起作用。
$(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>
您需要在委派后触发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>
您所做的一切都正确,除了一件事情-您在单击本身之后声明第二次单击的事件处理程序。 因此,触发第二次单击时,您尚未声明处理程序,也看不到任何警报。 我在下面重新排列了它。 尝试运行以下代码段。
$(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.