如何使用 jquery 每个函数从每个 li 获取数据?
我有一个无序列表,每个列表元素都有data-id"属性,想法是使用JQuery的每个函数遍历每个列表元素并获取data-id"值并动态分配位置,即制作一个项目滑块,一次滑动一个项目.但是我得到的每个数据的值都是1",即它只从第一个元素中获取值,我该如何解决??
I have a unordered list and each list element have "data-id" attribute, the idea is that using JQuery's each function iterate through each list element and get the "data-id" value and dynamically assign the position, ie to make a item slider that slides one item at a time. but on each the value of data I'm getting is "1", ie its taking value from the first element only, how do I fix it??
HTML
<div class="explore_matches">
<p>Recent Matches</p>
<ul class="clearfix item-slider">
<li data-id="1" ><span>1</span></li>
<li data-id="2" ><span>2</span></li>
<li data-id="3" ><span>3</span></li>
<li data-id="4" ><span>4</span></li>
<li data-id="5" "><span>5</span></li>
<li data-id="6" "><span>6</span></li>
<li data-id="7" "><span>7</span></li>
<li data-id="8" "><span>8</span></li>
</ul>
<button name="pre">Pre</button>
<button name="next">Next</button>
</div>
JavaScript
var item_width = $('.item-slider').width();
var item_margin = (item_width-600)/5;
var items = $('ul.item-slider>li');
$.each(items,function(index){
var pos = $('.item-slider > li').data('id') * 150;
if(index === 0)
$(this).css("left", pos);
else
$(this).css("left", pos + index * item_margin);
console.log(pos);
})
推荐答案
直接替换
var pos = $('.item-slider > li').data('id') * 150;
与
var pos = $(this).data('id') * 150;
相关文章