获取特定数据属性的所有值

时间:2017-07-03 20:36:06

标签: jquery

我看到data-tablet-src不止一个,我想用键和值列出它们,例如:

data-tablet-src => https://unsplash.it/1000/300?image=21
data-tablet-src => https://unsplash.it/1000/300?image=1001
bla...bla..bla...



$(document).ready(function(){
$('#mycarousel .item img[data-tablet-src]').each(function (index, value) { 
 alert("index:" + index+"value: "+value);
});

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="carousel-inner" role="listbox">
    <div class="item active">
        <img src="https://unsplash.it/1000/300?image=68" data-tablet-src="https://unsplash.it/1000/300?image=21">
    </div>
    <div class="item">
        <img src="https://unsplash.it/1000/300?image=43" data-tablet-src="https://unsplash.it/1000/300?image=1001">
    </div>
    <div class="item">
        <img src="https://unsplash.it/1000/300?image=67" data-tablet-src="https://unsplash.it/1000/300?image=1002">
    </div>
    <div class="item">
        <img src="https://unsplash.it/1000/300?image=47" data-tablet-src="https://unsplash.it/1000/300?image=1005">
    </div>
    <div class="item">
        <img src="https://unsplash.it/1000/300?image=72" data-tablet-src="https://unsplash.it/1000/300?image=63">
    </div>
  </div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您可以根据像

这样的元素索引将数据值映射回数组
var sources = $('.carousel-inner .item img').map(function() {
    return $(this).data('tablet-src');
}).get();

FIDDLE