![](/img/trans.png)
[英]how to access custom data-* html5 attribute placed in different tag, commonly in jquery?
[英]jquery access html5 custom data attribute in JSON format
我使用php构建了具有自定义数据属性的表格行:
<tr id="92280001" style='font-weight:bold' data-seqSet={'set':'1',seq1:'foo',seq2:'bar'}>
在我的脚本中,当单击表行时,我需要获取这些值(set,seq1,seq2):
isSet=$(this).closest('tr').data('seqset').set;
console.log(isSet);
它给了我不确定的东西。 我需要等于1。但是当我使用时:
isSet=$(this).closest('tr').data('seqset');
console.log(isSet);
然后,它将打印整个JSON。 我想念什么?
您的属性不是JSON。 因此,jQuery无法将此字符串解析为JSON。 基本上,它使用try-catch块进行检查,如果它能够解析它,则jQuery返回对象作为.data
调用的结果。
将其设置为有效的JSON字符串即可使用:
data-seqSet='{"set": "1", "seq1": "foo","seq2": "bar"}'
请注意,如何用"
正确引用属性。
这是一个用于将属性字符串转换为对象的函数: https : //github.com/jquery/jquery/blob/1777899a747647f3fa839eea4b0bb695d3b60f06/src/data.js#L42 (从https://github.com/jquery/调用jquery / blob / 1777899a747647f3fa839eea4b0bb695d3b60f06 / src / data.js#L153 )。
正如@dfsq向我指出的那样,如果检测到格式正确的JSON字符串,则jQuery .data()会将属性解析为一个对象。 因此,解决方案是更正JSON格式,以将键值包装在"
data-seqSet = {"set": "1", "seq1": "foo", "seq2": "bar"}
isSet = $(this).closest('tr').data('seqset').set;
alert(isSet);
在php中,echo必须为: echo "<tr id='92280001' style='font-weight:bold' data-seqSet='{\\"set\\":\\"1\\",\\"seq1\\":\\"foo\\",\\"seq2\\":\\"bar\\"}'>";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.