Thursday 4 August 2016

javascript - dynamically loaded content click event not firing



Currently, I am dynamically loading HTML via a dropdown click event (via jquery event)
The problem that arises is my .on event function is not finding the selector to fire the "a" tag click event.
If the original page that is loaded contains html with the "a" tag with the specified class, the click event for that "a" tag works fine, BUT if I dynamically load new content via the jquery event, then IF a clickable "a" tag exists and I click it, the original page just posts back, there is no evidence of the "a" tags click event firing.



Here is a sample of the dynamically loaded content;






Recipe Directions



  1. Pre-Heat oven to 350°, Grease two 9" springform pans

  2. Sift all dry ingredients into a large bowl

  3. Add corn oil, eggs and vanilla, mix well

  4. Fold in walnuts, coconut, carrots and pineapple

  5. Pour batter into the greased pans

  6. Bake for 50 minutes on the middle racks



Click  href="#">here  for frosting recipe









Here is how the content is loaded, the html is retrieved via a WCF service which I've confirmed is working;




function resetRecipeHtml(html, recipename) {
$("#lblRecipeLegend").text("Recipe for " + recipename);
$("#recipecard").html(html);


}



Here is the jquery event code, for now this code is just in a script block on the page outside the document ready code ( doesn't work if it's in it either) Note: The alert is there only to prove the event is firing.;




 $('#recipedirections p').on('click', 'a.icing', function (e) {
e.preventDefault();
var filename = $(this).attr("id");
alert(filename);
getRecipeHtml(filename);
});

Answer



Part of your question




Here is a sample of the dynamically loaded content;










As, recipedirections is also a part of dynamically loaded content. You should use document or nearest static container. You should use recipecard




 $("#recipecard").on('click', 'a.icing', function (e) {
e.preventDefault();
var filename = $(this).attr("id");
alert(filename);
getRecipeHtml(filename);
});

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...