A good way to hide some data behind <li> that can be retrieved during a click?
I create a page using jsp, it has a list item that shows several report names. When creating a list, I would like to hide the identifier of each report in the element of the list element, so that when the user clicks on this element, I can use ajax to retrieve it from the server, since I know the identifier. What a good way to do this so that jquery can easily pick up an id on a click? Right now I have something like:
// jsp pseudocode <ul id='reports'> <% for (all reports) { %><li><%= report.getTitle() %> <div class='hidden'><%= report.getId() %></div> // the hidden id for this item </li> <% } </ul> // click handler for the list. $('#reports').delegate('li', 'click', function() { var idOfTheClickedReport = ?; fetchReportById(idOfTheClickedReport); ... }); Is there a better way to do this?
thanks
I would not suggest using a hidden div this way. This is a lot of extra markup for id , and you are not currently using the id or rel attribute (both potential candidates for storing this information):
Since the concept of an identifier already exists in HTML, I think it makes sense to use this:
<ul id='reports'> <% for (all reports) { %> <li id="report-<%= report.getId() %>"><%= report.getTitle() %></li> <% } %> </ul> This will lead to the conclusion:
<ul id='reports'> <li id="report-1">Title Here</li> <li id="report-19">Title Here</li> <li id="report-27">Title Here</li> </ul> Then in your jQuery part (assuming id will not contain - ):
$('#reports').delegate('li', 'click', function() { var idOfTheClickedReport = this.id.split('-').pop(); fetchReportById(idOfTheClickedReport); ... }); The HTML5 way to do this will store data in an attribute of an element whose name begins with data- , for example:
<li data-reportid='<%= report.getId() %>'><%= report.getTitle() %></li>