Saturday, 16 September 2017

c# - jQuery click event not firing on dynamically added content




I have the body of a table which is appended dynamically with ajax to the table element through a partial view in ASP.NET MVC. The partial view looks something like this...



@model IEnumerable

@{
Layout = null;
}
@foreach (var plan in Model)
{


@plan.Name



}


...and appended to the table element which is static in the main View...







I am trying to register an onclick event for each of these anchor elements (there are a lot currently), using the jQuery on() function like this...




jQuery('#myPlanTable').on('click', 'tbody > tr:gt(0) > td > a.jumpToMyPlans', function () {
console.log('click');
});


...but the event refuses to fire. I've checked the DOM traversal in the browser console and it's definitely correct and returns the expected DOM set.


Answer



This selection statement worked for me....




jQuery('#myPlanTable').on('click', 'tr:gt(0) > td > a.jumpToMyPlans', function () {
console.log('click');
});


I think the problem was specifying tbody in the selector, which I guess is probably also dynamically generated, though not by me, I guess by the browser or something.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...