Reputation: 6324
I have this link inside one of the 2 tabs in my page but whenever I click on a.editReview
the page get reloaded and e.preventDefault()
seems not working. I know the problem is somewhere else but I can't really see it.
$(document).ready(function() {
/* Activate our reviews */
$().reviews('.starReviews');
$('.tabs a').on("click", function() {
var $this = $(this);
$('.panel').hide();
$('.tabs a.active').removeClass('active');
$this.addClass('active').blur();
var panel = $this.attr('href');
$(panel).fadeIn(250);
return false;
});//end click
$('.tabs li:first a').click();
$("a.editReview").on("click", function(e) {
e.preventDefault();
var reviewId = $(this).data('review-id');
alert(reviewId);
}); //edit review click function
});//document ready function
<div class="eventFeedbackBottomContainer">
<div class="tabs">
<ul>
<li><a href="#panel1" tabindex="1">Reviews</a></li>
<li><a href="#panel2" tabindex="2">Hotels</a></li>
</ul>
</div>
<div class="rightFeedbackBottomContainer">
<a href="/addReview/<?php echo escape($eventReview->getData()->race_id);?>/" id="" class="Smallbut">Add Review</a>
</div>
<div id="panel1" class="panel">
<div class="feedbacksContainer">
<div class="show-reviews"></div><!-- a.editReview is inside each review loaded from a javascript file in this div-->
</div>
</div>
<div id="panel2" class="panel"/>
</div>
UPDATE
As suggested by dfsq I started reading about delegation and this is a good start for whoever is struggling to understand it, like myself! Delegation
Upvotes: 3
Views: 169
Reputation: 193261
This is the situation when you need to deletage event to a parent container:
$(".eventFeedbackBottomContainer").on("click", "a.editReview", function(e){
e.preventDefault();
var reviewId = $(this).data('review-id');
alert(reviewId);
});
This is the case because links are loaded dynamically after DOMContentLoaded event, you don't have .editReview
links available on page load so you can't bind event to them. But you can bind click event listener to a parent container for example .eventFeedbackBottomContainer
and listen all click events bubbling from all child elements up the DOM tree. This way even if you inject relevant links later, your event listener will be able to detect clicks on them.
Upvotes: 5
Reputation: 1236
Try Like this, It will work:
$("a.editReview").click(function(e){
e.preventDefault();
var reviewId = $(this).data('review-id');
alert(reviewId);
});
Upvotes: -2