简体   繁体   English

jQuery内联属性值

[英]Jquery inline attribute value

Can i get some suggestions. 我能得到一些建议吗? Do you have better way to do this? 您有更好的方法吗?

Most of the time when i got a group of data input in Html table, I always level data like some reference id like "student_id", or "country_id" to parent structure like or , 在大多数情况下,当我在Html表中输入一组数据时,我总是将诸如“ student_id”或“ country_id”之类的引用ID的数据级别化为诸如或的父结构,

for example 例如

<tr student_id="1" subject_id="2" school_id="5" country_id="6">
 <td></td>
 <td></td>
 <td></td>
 <td></td>
  .....
  ......
</tr>
....
.....

<tr student_id="43" subject_id="35" school_id="22" country_id="411">
 <td></td>
 <td></td>
 <td></td>
 <td></td>
  .....
  ......
</tr>
....
.....

when i call javascript function i can get and get those id in function 当我调用javascript函数时,我可以获得函数中的ID

var tr  = $(this).closest('tr');
var student_id =  $(this).attr('student_id');
var subject_id =  $(this).attr('subject_id');
var school_id =  $(this).attr('school_id');
.......

Do you got better way to store these kind of reference ? 您有更好的方法来存储这些参考吗? Thanks. 谢谢。

The HTML5 way of doing this that is backwardly compatible with older browsers and has specific support in jQuery is with data-xxx attributes. 与旧版浏览器向后兼容并在jQuery中具有特定支持的HTML5方法是使用data-xxx属性。

<tr data-student_id="43" data-subject_id="35" data-school_id="22" data-country_id="411">

var tr  = $(this).closest('tr');
var student_id = tr.data('student_id');
var subject_id = tr.data('subject_id');
var school_id = tr.data('school_id');

One of the rationales behind doing it this way in HTML5 is this puts all custom data attributes in the "data-" namespace which is guaranteed to never conflict with future standard attributes that might be defined on any HTML tag. 在HTML5中以这种方式执行此操作的基本原理之一是,将所有自定义数据属性放在"data-"命名空间中,这保证不会与将来可能在任何HTML标记上定义的标准属性冲突。 In jQuery, it also unifies it with the .data() method of storing per object data. 在jQuery中,它还与.data()方法统一存储每个对象数据。

Note, when using jQuery's .data(key) method, it also tries to convert the data to a native javascript type so in your case above, it would convert those values to numbers automatically. 注意,当使用jQuery的.data(key)方法时,它还会尝试将数据转换为本地javascript类型,因此在上述情况下,它将自动将这些值转换为数字。

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

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