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

+4
source share
4 answers

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); ... }); 
+1
source

What you do is perfectly reasonable.

An alternative approach would be to use jQuery data() to store arbitrary data for an element.

+2
source

You can save id as arbitary html property like

 <li reportid='<%= report.getId() %>'><%= report.getTitle() %></li> 

Will work, you can get the identifier var idOfTheClickedReport = $ (this) .attr ('reportid');

it is not standard compatible HTML, but it should work well in any browser.

+2
source

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> 
+2
source

Source: https://habr.com/ru/post/1313291/


All Articles