如何从数据属性获取数据密钥名称?(How to get data key name from data attribute?)

编程入门 行业动态 更新时间:2024-10-16 16:45:17
如何从数据属性获取数据密钥名称?(How to get data key name from data attribute?)

我想从我的HTML元素获取关键名称?

示例代码:

<td data-code="123">220</td>

使用jquery数据方法我能够键值,但我想提取键名?

var keyValue=$("td").data("code"); //123 var keyName=?????

I want to get key name from my html element?

Sample code :

<td data-code="123">220</td>

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=?????

最满意答案

数据代码将是关键。

如果你想获得未知键/值对的键,你可以使用for (var key in data) {}循环:

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]

data-code would be the key for that.

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]

更多推荐

本文发布于:2023-07-15 05:45:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1110763.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据   密钥   属性   名称   attribute

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!