Brief description of what I'm attempting to do:
I'm developing a small web application where I'm posting comments with AJAX. So I'm using the $.post method and jQuery templates to do that. All is fine there. However, I'm also attempting to make a like button where the user should be able to like each post.
So my first problem is that I need to store the comment ID in the like link somehow
(I think), please correct me if I'm wrong. So the best way I could conceive of to do that was to use the .data() function in jQuery.
So what I do to post the posts and
add the comment ID to the like link is:
- $.post("/Home/Create", comment, function (data) {
- var totalItems = data.length;
- var currentItems = $(".list-group-item").size(); /
-
- //In data is a list of all the posts, so I need to loop through the new ones and add them
- for (var i = currentItems; i < totalItems; i++) {
- $("#CommentList").loadTemplate($("#CommentTemplate"), {
- Username: data[i].Username,
- CommentText: data[i].CommentText,
- CommentDate: data[i].CommentDate
- }, { append: true });
- //Not sure how to add .data() to an item through loadTemplate, so I just select the last (newest) item in the list and add it below
- var temp = $(".list-group-item").last();
- temp.data("comment", data[i].ID);
alert(temp.data("comment")); //Works
The reason for why I'm attempting to
add the commentID to the anchor tag is so I can use the
on click event of the anchor tag and
reach the commentID somehow, so I can save the like for that comment.
Is there another (much better?) way to do this?
Where I
run into problems is, in the on click event, I try to write out $(this).data("comment"), I get the value
undefined. I'm not sure why.
Here's the onclick event:
- $(document).on("click", ".like-comment", function () {
- alert($(this).data("comment")); //Writes out undefined for some reason..
- });