javascript - Why are only half the element's classes able to be toggled? -
i'm utilizing jquery's .toggleclass() function create favorite button inside several <div>
elements, each has <a>
element, , <i>
element. i'm using 2 icons font awesome classes i'm toggling , forth between.
this works fine demonstrated jsfiddle.
the issue i'm having when dynamically generate these elements using php foreach loop half of generated element's classes toggle.
html :
<div> <a class="h-icon" href="#"> <i class="fa fa-heart-o" aria-hidden="true"></i> </a> </div> <div> <a class="h-icon" href="#"> <i class="fa fa-heart-o" aria-hidden="true"></i> </a> </div> <div> <a class="h-icon" href="#"> <i class="fa fa-heart-o" aria-hidden="true"></i> </a> </div> <div> <a class="h-icon" href="#"> <i class="fa fa-heart-o" aria-hidden="true"></i> </a> </div> <div> <a class="h-icon" href="#"> <i class="fa fa-heart-o" aria-hidden="true"></i> </a> </div> <div> <a class="h-icon" href="#"> <i class="fa fa-heart-o" aria-hidden="true"></i> </a> </div>
jquery :
$(".h-icon").on("click", function(e) { e.preventdefault(); $("i", this).toggleclass("fa-heart fa-heart-o"); $.ajax({ url: $(this).prop("href") }) return false; });
php :
<?php foreach($array $row) { $favorite = $row['favorite']; if($favorite == false) { echo '<div><a class="h-icon" href="#"><i class="fa fa-heart-o" aria-hidden="true"></i></a></div>'; } else { echo '<div><a class="h-icon" href="#"><i class="fa fa-heart" aria-hidden="true"></i></a></div>'; } } ?>
when dynamically add more elements need register click
listener again, or use dynamic event listener.
$(document).on("click", ".h-icon", function(e) { // ... });
Comments
Post a Comment