具有数据attr的Div元素获得具有相同data-attr div

时间:2017-09-07 10:57:01

标签: javascript jquery

我的结构如下

<div data-example="1"></div>
<div data-example="2"></div>
<div data-example="1"></div>
<div data-example="3"></div>
<div data-example="2"></div>
<div data-example="2"></div>
<div data-example="4"></div>

对于这种结构,可以使用不同的值数据添加额外的div - 例如4-5-6-9等。

我想获取具有相同数据示例attr的div的索引并将其添加为html元素。例如

<div data-example="1">Index is 0 for data 1</div>
<div data-example="2">Index is 0 for data 2</div>
<div data-example="1">Index is 1 for data 1</div>
<div data-example="3">Index is 0 for data 3</div>
<div data-example="2">Index is 1 for data 2</div>
<div data-example="2">Index is 2 for data 2</div>
<div data-example="4">Index is 0 for data 4</div>

详情

数据1的索引为0这是第一个具有1值的数据示例的div,这是div中的第一个div,其数据示例值为1,其索引为0,第二个div为data-example = 2得到索引1.

如何使用jquery动态获取索引。

2 个答案:

答案 0 :(得分:2)

您必须使用如下所示的jQuery prevAll(): -

&#13;
&#13;
$('div').each(function(){
  var attr = $(this).attr('data-example');
  if (typeof attr !== typeof undefined && attr !== false) {
    var counter = $(this).prevAll('div[data-example='+$(this).data('example')+']').length;
    $(this).text("Index is "+counter+" for data "+$(this).data('example'));
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div data-example="1"></div>
<div data-example="2"></div>
<div data-example="1"></div>
<div data-example="3"></div>
<div data-example="2"></div>
<div data-example="2"></div>
<div data-example="4"></div>

<div>Unchanged</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以使用过滤功能。

&#13;
&#13;
var allItems = $("div").filter("[data-example]");

var mV = 0;
if (allItems.length > 0) {
  $(allItems).each(function(k, v) {
    var val = $(this).attr("data-example");
    if (mV < val) mV = val;
  })

  for (var ic = 1; ic <= mV; ic++) {
    $(allItems).filter("[data-example='" + ic + "']").each(function(key, value) {
      //console.log(key);  //  this is index
      //Here updated the div text correctly.
      $($(this)[0]).html("Index is " + key + " data " + ic);
    });
  }
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-example="1">Index is 0 for data 1</div>
<div data-example="2">Index is 0 for data 2</div>
<div data-example="1">Index is 1 for data 1</div>
<div data-example="3">Index is 5 for data 3</div>
<div data-example="2">Index is 1 for data 2</div>
<div data-example="2">Index is 0 for data 2</div>
<div data-example="4">Index is 0 for data 4</div>
&#13;
&#13;
&#13;

参考:https://stackoverflow.com/a/2903048/7974050