Tuesday, July 31, 2012

jquery correct way to dynamically populate elements and do callbacks specific to each one?



I\’m trying to figure out the best way to do this in jquery. I\’m GETting some data via an ajax call, and stuffing that into the page. We\’re dealing with a simple note taking application. Each note has its own set of data.

I\’ve included the code that I\’m woring with currently. The notes stuffed into the DOM have multiple methods(as links,) which are to do different things, e.g. save, delete, revert. When those are clicked, I want to make another ajax call and do a POST. But, how do I figure out which sticky note the save, or delete came from?


How should I handle the click events? Should I make a selector for the id of every dynamic element? That does not sound ideal, and I don\’t know how to do that either.

Can I have one event handler that makes an anonymous function and parses the id, where the id contains a unique identifier and a directive, such as save, delete, etc.

Neither of these two seem like the best option. What does stackoverflow recommend?



<html xmlns=\'http://www.w3.org/1999/xhtml\'>
<head>
<meta http-equiv=\'Content-Type\' content=\'text/html; charset=utf-8\'/>
<link rel=\"stylesheet\" type=\"text/css\" href=\"layout.css\" />
<script type=\"text/javascript\" src=\"jquery-1.7.1.min.js\"></script>
<script type=\"text/javascript\">
$.ajax({
url: \'noteGet.php\',
data: \"\",
dataType: \'json\',
success: function(rows)
{
for (var i in rows) {
var noteId = rows[i][0];
var noteContent = rows[i][2];
$(\'#allNotes\')
.append(\'<span id=\"stickyNote\'+noteId+\'\" class=\"stickyNote\"><textarea id=\"stickyNoteTextArea\'+noteId+\'\" class=\"stickyNoteTextArea\">\'+noteContent+\'</textarea><a href=\"#\" id=\"stickyNoteSave\'+noteId+\'\">save</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"#\" id=\"stickyNoteDelete\'+noteId+\'\">delete</a></span>\')
}
}
});


$(\'#allNotes\').on(\'click\', \'a\', function() {
//what to do
});

});
</script>

</head>
<body>
<span id=\"links\"></span>
</body>
</html>






Rating: 5 out of 5 based on 3 ratings



The post jquery correct way to dynamically populate elements and do callbacks specific to each one? appeared first on Javascript ASK.






via Javascript ASK http://javascriptask.phpfogapp.com/jquery-correct-way-to-dynamically-populate-elements-and-do-callbacks-specific-to-each-one.html

No comments:

Post a Comment