I have a function that looks like this:
$(".container").on("click", ".comment:first-child > .like_btn", function () {
console.log("it works!");
});
The .comment
in the .container
get dynamically added. What I'd like to do is detect if there was a click on the like button of the first comment. However, what I have right now doesn't work. What am I doing wrong?
HTML
<div class="container">
<div class="comment"> //Dynamically added
<div class="like_btn"></div>
</div>
</div>
EDIT: There are no errors, just that the click event doesn't fire.
Try attaching your handler to the document
instead:
$(document).on("click", ".container .comment:first-child > .like_btn", function() { console.log("it works!"); }); setTimeout(() => $(".comment").append("<div class='like_btn'>Like!</div>"), 2000);
<script src="https://code.jquery.com/jquery-3.3.1.js"></script> <div class="container"> <div class="comment"> //Dynamically added </div> </div>
One solution is to use event delegation on the document
element, like this:
$(document).ready(function() { $(".container").append( `<div class="comment"> <div class="like_btn">LIKE 1</div> </div> <div class="comment"> <div class="like_btn">LIKE 2</div> </div>` ); }); $(document).on("click", ".container .comment:first-child > .like_btn", function() { console.log("it works!"); });
.as-console {background-color:black !important; color:lime;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container"> </div>
However, if the .container
element is not added, also, dynamically, then your code should work fine as shown on next example:
$(document).ready(function() { $(".container").append( `<div class="comment"> <div class="like_btn">LIKE 1</div> </div> <div class="comment"> <div class="like_btn">LIKE 2</div> </div>` ); }); $(".container").on("click", ".comment:first-child > .like_btn", function() { console.log("it works!"); });
.as-console {background-color:black !important; color:lime;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container"> </div>
尝试删除“>”
$('.container .comment .like-btn').on('click', function(){ //do something })
$(document).ready(function() { $(".container").append( `<div class="comment"> <div class="like_btn">LIKE 1</div> </div> <div class="comment"> <div class="like_btn">LIKE 2</div> </div>` ); }); $(document).on("click", ".container div:first-of-type > .like_btn", function() { console.log("it works!"); });
.as-console {background-color:black !important; color:lime;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container"> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.