Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
6
rated 0 times [  9] [ 3]  / answers: 1 / hits: 16378  / 12 Years ago, sat, september 29, 2012, 12:00:00

I have this loop creating several divs with elements in it. I want to be able to attach a click event to every link with the linky class, and this link would read the contentID attribute.



I've searching forever, find cases to use selectors in dynamic created elements but just can't apply to my case. Any tips?



                    for (i = 0; i < msg.length; i++) {
var htmlCode = <a href='/Controller/Details/ + msg[i].ID + ' style = 'float: left;'><img class='packageImage' border='0' src=' + msg[i].Size0Path + ' /></a>;
htmlCode += <span style='float: left;margin: 5px 0px 0px 10px;'> + <b> + msg[i].TheName + </b><br>;


if (msg[i].IsPaused == true) {

htmlCode += <a href='#bar' class=linky contentID=' + msg[i].ID + '>Resume</a>;
} else {

htmlCode += <a href='#bar' class=linky contentID=' + msg[i].ID + '>Pause</a>;
}
htmlCode += </span>;
htmlCode += <div class='clear'></div>;
$(#divContent).append(htmlCode);
}


Given the answers, I'm trying to attach the event to class linky, but I just not sure where, see more details below, my instructions are creating the dynamic Elements from the result of ajax submit(post).



                    success: function (msg) {

$(body).on(click, a.linky, function () {
alert($(this).attr(contentID));
});



for (i = 0; i < msg.length; i++) {
var htmlCode = <a href='/Controller/Details/ + msg[i].ID + ' style = 'float: left;'><img class='packageImage' border='0' src=' + msg[i].Size0Path + ' /></a>;
htmlCode += <span style='float: left;margin: 5px 0px 0px 10px;'> + <b> + msg[i].TheName + </b><br>;


if (msg[i].IsPaused == true) {

htmlCode += <a href='#bar' class=linky contentID=' + msg[i].ID + '>Resume</a>;
} else {

htmlCode += <a href='#bar' class=linky contentID=' + msg[i].ID + '>Pause</a>;
}
htmlCode += </span>;
htmlCode += <div class='clear'></div>;
$(#divContent).append(htmlCode);
}


}

More From » jquery

 Answers
93

Use the delegated form of on:



$(body).on(click, a.linky, function() {
alert($(this).attr(contentID));
});


You only need to do this once, before creating any dynamic content. It will attach an event handler to <body> that will respond to any of its descendants that satisfy the a.linky selector being clicked. It does not matter if these elements are already in the DOM at the moment you attach the handler or if they get added later.


[#82839] Friday, September 28, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
juand

Total Points: 366
Total Questions: 95
Total Answers: 90

Location: Wallis and Futuna
Member since Tue, Mar 30, 2021
3 Years ago
;