Reputation: 1948
I have a list of items that are filled dynamically:
function ViewData(data) {
var SI = (typeof data) == 'string' ? eval('(' + data + ')') : data;
$('#ListContainer').empty();
for (var i = 0; i < SI.length; i++) {
var text = '<a href="Page.htm" rel="external" onclick= "SaveData();"
class="lesson" LessonID="' + SI[i].lessonID
'"><span class="lesson_subject">' + SI[i].sbj_Name +
'</span></b></a>
$('#ListContainer').append(text).trigger("create");
}
}
When one item of them is clicked, the page should navigate to another page carrying the data of this link.
I made this function to save the values of found in the link:
function SaveData() {
localStorage["LessonID"] = $('#ListContainer').find('.lesson').attr('LessonID');
localStorage["SubjectName"] = $('#ListContainer').find('.lesson_subject').text();
}
but it saves "All of the data". I want to save the data of the selected item only. Do you have any ideas ? Thanks.
Upvotes: 1
Views: 527
Reputation: 13471
Change this
onclick= "SaveData();"
to
onclick= "SaveData(this);"
Then change the saveData
function to
function SaveData(elem) {
localStorage["LessonID"] = $(elem).attr('LessonID');
localStorage["SubjectName"] = $(elem).find('.lesson_subject').text();
}
Or even better, you can use $.on
like @James Allardice showed in his answer.
Upvotes: 3
Reputation: 6357
You're mixing old world JavaScript and jQuery.
Use $("<a ...")
to create your element, append it and then attach a .click handler which can use $(this)
when it is fired. Use .data to add data to the elements when you add them which the .click handler can utilise.
Upvotes: 1
Reputation: 166061
It saves all of the data because your find('.lesson')
will find every link inside #ListContainer
. I would suggest removing your inline event handlers and taking advantage of event delegation with the on
method:
$("#ListContainer").on("click", ".lesson", function() {
localStorage["LessonID"] = $(this).data("lessonid");
localStorage["SubjectName"] = $(this).data("subject");
});
Notice that I've used the data
method instead of attr
. That will require another change to your markup:
<a href="Page.htm" rel="external" class="lesson" data-lessonid="someID" data-subject="someSubject">
This uses HTML5 data-*
attributes, which are the recommended approach when it comes to storing arbitrary data on an element.
Why use event delegation? It is more efficient, as it results in less event handlers bound to elements. Instead of one on every a.lesson
element, there is just one on the #ListContainer
element.
Because most DOM events bubble up the tree, a click on a descendant of #ListContainer
will bubble up through the DOM tree, eventually reaching #ListContainer
. The jQuery on
method will pick up the event at this element, and check to see if it originated at an element matching .lesson
. If so, it will execute the event handler.
Upvotes: 5