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

时间:2022-04-04 19:35:06

How can I set data-slide-to, same as I set id for each li#myCarousel

我如何设置data-slide-to,就像我为每个li#myCarousel设置id一样

HTML

I have set ids 0, 1 ...

我设置了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;

I need set also data-slide-to 0, 1 ...

我还需要设置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 OUTPUT I NEED

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 done i have replace js to *

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

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

1 个解决方案

#1


0  

You set the ID based on the index of the for loop, at the same time you can also set the data attribute:

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

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);
}

#1


0  

You set the ID based on the index of the for loop, at the same time you can also set the data attribute:

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

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);
}