简体   繁体   English

如何使用HTML5数据属性获取会话属性

[英]How to use an HTML5 data attribute to get session attribute

I'm new to the front end side of Java EE and HTML5. 我是Java EE和HTML5前端的新手。 I have read that you could use the data attribute to read through the DOM. 我已经读过您可以使用data属性来读取DOM。 How would you properly use this to get a session attribute already set by java. 您将如何正确地使用它来获取Java已经设置的会话属性。 Compared to the other methods such as using a hidden input. 与其他方法相比,例如使用隐藏输入。

<input id="sid" type="hidden" name="series" value="${sessionScope.series} />

var sid = document.getElementById("sid"), series;

Use something like this: 使用这样的东西:

<div id="div1" data-special-value="${sessionScope.series}"></div>

And get the attribute value like: 并获得如下属性值:

document.getElementById("div1").getAttribute("data-special-value")

Or even ( http://caniuse.com/dataset ): 甚至( http://caniuse.com/dataset ):

document.getElementById("div1").dataset("special-value")

Or with jQuery: 或使用jQuery:

$("#div1").attr("data-special-value")
// or
$("#div1").data("special-value")

Although I'm not sure storing a session value on an element is right. 尽管我不确定将会话值存储在元素上是否正确。 It's definitely not wrong, I'm just wondering what you'd need/use it for with sessions. 绝对没有错,我只是想知道您在会话中需要/使用什么。 Sessions appear once. 会话出现一次。

The data-* attributes are more useful with storing related data to something. data-*属性在将相关数据存储到某物时更有用。 For example, if you loop through a bunch of database records and print their columns, but want to also store the row's database id once, you'd use: 例如,如果您遍历一堆数据库记录并打印它们的列,但又想一次存储该行的数据库id ,则可以使用:

<c:forEach items="${rows}" var="row">
    <tr data-row-id="${row.id}">
        <td>${row.name}</td>
        <td>${row.description}</td>
    </tr>
</c:forEach>

Then if you want to get the original row.id value, it's stored in one place an encompasses everything it pertains to (the columns). 然后,如果您想获取原始的row.id值,则将其存储在一个地方,其中包含与之相关的所有内容(各列)。 This is usually how/where I use data-* attributes. 这通常是我使用data-*属性的方式/位置。 Of course, there are many ideas/uses for this. 当然,有很多想法/用途。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM