Friday, November 1, 2019

javascript - jQuery click not working for dynamically created items




I have a piece of jQuery that loops through each element in a given div( #container) and does a javascript alert each time a span is clicked. This works fine if the 's are static.



However, if I use a piece of code like:




$(someLink).click(function(){
$("#container").html( )
});


The jQuery code doesn't fire off. Oddly enough though



My question is : Is there a reason my Click events don't work for dynamically created items? I assume I will have to add something into my document ready or heartbeat-script (which is fired every 100 miliseconds) to hook up the events??


Answer



Do this:




 $( '#wrapper' ).on( 'click', 'a', function () { ... });


where #wrapper is a static element in which you add the dynamic links.



So, you have a wrapper which is hard-coded into the HTML source code:







and you fill it with dynamic content. The idea is to delegate the events to that wrapper, instead of binding handlers directly on the dynamic elements.






Btw, I recommend Backbone.js - it gives structure to this process:



var YourThing = Backbone.View.extend({

// the static wrapper (the root for event delegation)

el: $( '#wrapper' ),

// event bindings are defined here
events: {
'click a': 'anchorClicked'
},

// your DOM event handlers
anchorClicked: function () {
// handle click event

}

});

new YourThing; // initializing your thing

No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...