jQuery如何查找数据元素值

时间:2016-01-28 22:00:07

标签: jquery html find each element

我有这个HTML代码:

<body>
....
<span data-code="code100">...</span>
....
<div data-code="code101">...</div>
<input type="test" ... data-code="code102">...</input>
...
<b data-code="code103">...</b>
etc...
</body>

现在我想找到[data-code]的所有元素并获取数据代码值(code100,code101,code 103,code104)

这不起作用:

var arr = $("[data-code]");
    $.each(arr, function(key) {
        alert($(key).data('data-code'));
    });

我该怎么做?

2 个答案:

答案 0 :(得分:1)

这项工作 -

var arr = $("[data-code]");
 $.each(arr, function(index, value) {
  alert($(this).data('code'));
});

您可以参考这样的数据值。您的数据密钥是“代码”。 阅读更多关于Jquery.data()here

的信息

答案 1 :(得分:0)

它对我有用。使用打开的开发人员控制台尝试此示例。

var arr = $("[data-code]");
$.each(arr, function(index, value) {
  console.log($(this).attr('data-code'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span data-code="code100"></span>
<div data-code="code101"></div>
<input type="test" data-code="code102" />
<b data-code="code103"></b>