我想从html元素中获取键名吗?

样例代码:

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


使用jquery数据方法,我可以输入值,但我想提取键名?

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]

10-05 20:33
查看更多