jQuery获得具有特定数据属性值的元素样式



我正在使用bxslider,我通过使用pagercustom选项创建了一个自定义的拨打器。我希望Pager看起来像缩略图Pager,因此我尝试复制每张幻灯片的样式并将其附加到每个Pager上。示例:Pager 1应该具有幻灯片1的样式,幻灯片2的Pager 2,依此类推..

这是我现在作为寻呼机的东西:

<div class="custom-pager">
 <a data-slide-index="0" href="" class="">1</a>
 <a data-slide-index="1" href="" class="active">2</a>
 <a data-slide-index="2" href="" class="">3</a>
 <a data-slide-index="3" href="" class="">4</a>
</div>

我的jQuery代码是:

$('#slider .custom-pager a').each(function(){
 var test = $(this).parent().index();
 $(this).attr('style', $('*[data-slide=" ' + test + ' "]').attr('style'));
});

我在每个BXSLIDER列表中添加了数据幻灯片:

<ul class="bxslider" style="width: auto; position: relative;">
    <li data-slide="0" style="background: transparent url(&quot;_assets_/images/slide-1.jpg&quot;) no-repeat scroll center center / cover ; float: none; list-style: outside none none; position: absolute; width: 1903px; z-index: 0; display: none;"></li>
    <li data-slide="1" style="background: transparent url(&quot;_assets_/images/slide-2.jpg&quot;) no-repeat scroll center center / cover ; float: none; list-style: outside none none; position: absolute; width: 1903px; z-index: 50; display: list-item;"></li>
    <li data-slide="2" style="background: transparent url(&quot;_assets_/images/slide-1.jpg&quot;) no-repeat scroll center center / cover ; float: none; list-style: outside none none; position: absolute; width: 1903px; z-index: 0; display: none;"></li>
    <li data-slide="3" style="background: transparent url(&quot;_assets_/images/slide-2.jpg&quot;) no-repeat scroll center center / cover ; float: none; list-style: outside none none; position: absolute; width: 1903px; z-index: 0; display: none;"></li>
</ul>

这个

$('*[data-slide=" ' + test + ' "]')

根据您的HTML有两种方式是错误的:

  • 您的属性是"数据 - 滑动索引"而不是"数据扫描"。
  • 您有额外的空间,在等式后您不需要这些空间(也不需要开始 *)。额外的空间意味着值应该是例如'1'而不是" 1"。

因此,您的选择没有选择任何东西。您可以使用:

$('[data-slide-index="' + test + '"]')

另外,考虑$()是否对您有用。不确定您要实现的目标。

如果您使用传递给.EAT()的索引,则不需要使用 test,另外,如@tigoldbitties所述,您在选择器上有一些额外的空格。尝试这个

$('#slider .custom-pager a').each(function(index){
    $(this).attr('style', $('[data-slide="' + index + '"]').attr('style'));
});

最新更新