如何从数据属性获取数据键名? [英] How to get data key name from data attribute?
本文介绍了如何从数据属性获取数据键名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从我的html元素中获取键名吗?
I want to get key name from my html element?
示例代码:
<td data-code="123">220</td>
使用jquery数据方法,我可以输入键值,但我想提取键名?
Using jquery data method I am able to key value but I want to extract key name?
var keyValue=$("td").data("code"); //123
var keyName=?????
推荐答案
数据代码将是实现这一目标的关键.
data-code would be the key for that.
如果要获取未知键/值对的键,可以使用for (var key in data) {}
循环:
If you want to get the keys for unknown key/value pairs you can use a for (var key in data) {}
loop:
var all_values = [],
data = $('td').data();
for (var key in data) {
all_values.push([key, data[key]]);
}
//you can now access the key/value pairs as an array of an array
//if $(td).data() returns: `{code : 123}` then this code would return: [ [code, 123] ]
//you could get the first key with: all_values[0][0] and its corresponding value: all_values[0][1]
这篇关于如何从数据属性获取数据键名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文