开发者

Good way to hide some info per <li> which can be extracted during a click?

I'm generating a page using jsp, it has a list element which shows a few report names. When generating the list, I'd like to hide the id of each report in the list item element so that when the user clicks that item, I can use ajax to fetch it from the server, since I know the id. What's a good way to do this such that it's easy for jquery to pick up the 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?

Thank you


What you're doing is entirely reasonable.

An alternative approach would be to use jQuery's data() call to store arbitrary data on an element.


You can store the id as an arbitary html property like

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

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

it's not standard compliant HTML, but it should work fine in any browser.


The HTML5 way to do it would be to store the data in an element attribute whose name starts with data-, like this:

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


I would not suggest using a hidden div that way. It is a lot of extra markup for an id, and you are not currently using the id or rel attribute (Both potential candidates for holding this information):

Since there is already the concept of an ID in HTML, I think it makes the most sense to leverage that:

<ul id='reports'>
   <% for (all reports) { %>
      <li id="report-<%= report.getId() %>"><%= report.getTitle() %></li>
   <% } %>
</ul>

This would output:

<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 (Assumes id will not contain a -):

$('#reports').delegate('li', 'click', function() {
    var idOfTheClickedReport = this.id.split('-').pop();
    fetchReportById(idOfTheClickedReport);
    ...
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜