我如何设置data-slide-to,就像我为每个.carousel-indicators li设置id一样

时间:2016-02-10 12:06:15

标签: javascript

如何设置data-slide-to,与我为每个li设置id相同#myCarousel

HTML

我设置了ID 0,1 ...

<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="" id="0"></li>
<li data-target="#myCarousel" data-slide-to="" id="1"></li>  
</ol>

JS

  var iD = document.querySelectorAll('.carousel-indicators li');
  // Set their ID
  for (var i = 0; i < iD.length; i++) 
  iD[i].id = + i;

我还需要设置data-slide-to 0,1 ...

JS

var dataslideto = document.querySelectorAll('.carousel-indicators li');
// Set their data-slide-to
for (var i = 0; i < dataslideto.length; i++)
dataslideto[i].data-slide-to = + i;

我需要的HTML输出

<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" id="0"></li>
<li data-target="#myCarousel" data-slide-to="1" id="1"></li> 
</ol>

* JOB完成后我将js替换为*

var i = 0;
$(".carousel-indicators li").each( function() {
$(this).attr("data-slide-to", +i);
$(this).attr("id", +i);
i++;
});

1 个答案:

答案 0 :(得分:0)

您可以根据for循环的索引设置ID,同时还可以设置数据属性:

var abcElements = document.querySelectorAll('.carousel-indicators li');
  for (var i = 0; i < abcElements.length; i++) {
  abcElements[i].id = + i;
  abcElements[i].setAttribute('data-slide-to', i);
}