How to "embed" partialView elements into the DOM to add jQuery code?
I have a partialView:
<table class="table table-bordered table-condensed table-hover table-striped">
<thead>
<tr>
<th>Trip Id</th>
<th>Start Time</th>
<th>End Time</th>
<th>Actual Distance</th>
<th>Air Distance</th>
<th>Avg Speed</th>
<th>Max Speed</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr class="trip" data-id="@item.TripId" data-url="@Url.Action("","")">
<td>@item.TripId</td>
<td>@item.StartTimeStamp</td>
<td>@item.EndTimeStamp</td>
<td>@item.ActualDistance</td>
<td>@item.AirDistance</td>
<td>@item.AvgSpeed</td>
<td>@item.MaxSpeed</td>
</tr>
}
</tbody>
</table>
which is loaded via jQuery function .load()
. However, I found that when it is loaded this way inside my site.js file, the class is .trip
not added to the DOM before it is loaded, and therefore I cannot write code that reacts to:
$(".trip").click()
How can I fix this problem?
NB: I have all Javascript / jQuery code inside mine site.js
Edit
Snapshot for loading partialView:
$("#TripPartial").slideUp('200', function () {
$('#TripPartial').load(_this.data('url'), { id: _this.data('id') }, function () {
$("#TripPartial").slideDown('200');
});
});
source to share
You must use event delegation
for items that were added dynamically.
You must bind your event handler click
with a method .on()
.
Delegation event allows us to attach a single event listener to the parent element that will fire for all descendants matching the selector, whether those descendants exist or are added in the future.
$(document).on('click','.trip',function(){
});
source to share