在jQuery中检索* all *子元素的数据属性

时间:2017-04-16 06:49:55

标签: javascript jquery html

我希望以数组的形式获取子元素的所有数据属性。

我试过

"data_array" : $('#rule-list').children().data('fruits')


 <div class="fruit-list" id="fruit-list">
        <span class="chips" title="Click to remove" data-fruit="apple,mango; pineapple, watermelon">every month for 5 times</span>
        <span class="chips" title="Click to remove" data-fruit="banana,kiwi">every May and November for 5 times</span>
    </div>

预期输出应为

data_array = [[apple,mango; pineapple, watermelon],[banana,kiwi]]

4 个答案:

答案 0 :(得分:2)

由于您要返回每个数组元素的属性值而不是单个元素的属性值,因此您无法使用jQuery#data(key)(因为它只返回data-*属性jQuery集合中的第一个元素。)

我建议在调用Array#map时使用getAttribute代替:

var fruitList = document.getElementById('fruit-list')

var dataArray = [].map.call(fruitList.children, function (e) {
  return e.getAttribute('data-fruit')
})

console.log(dataArray)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fruit-list" id="fruit-list">
        <span class="chips" title="Click to remove" data-fruit="apple,mango; pineapple, watermelon">every month for 5 times</span>
        <span class="chips" title="Click to remove" data-fruit="banana,kiwi">every May and November for 5 times</span>
    </div>

答案 1 :(得分:1)

&#13;
&#13;
var elements = document.querySelectorAll('[data-fruit]');
var result = [];
for(var i=0; i < elements.length; i++) {
    result.push([elements[i].dataset.fruit]);
}

console.log(result);
&#13;
<div class="fruit-list" id="fruit-list">
<span class="chips" title="Click to remove" data-fruit="apple,mango; pineapple, watermelon">every month for 5 times</span>
<span class="chips" title="Click to remove" data-fruit="banana,kiwi">every May and November for 5 times</span>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

你可以这样做

var fruitArray=[] // Array to contain array of fruits
// will get all children
var getChild = $("#fruit-list").children();
// loop over them
getChild.each(function(i,v){
// push in fruits array, an array of data-fruit
fruitArray.push([($(v).data('fruit'))])
})
console.log(fruitArray)

DEMO

答案 3 :(得分:1)

您可以使用选择器"#fruit-list [data-fruit]" $.map().match()RegExp /\w+/作为参数来匹配一个或多个单词字符,返回一个带有返回值的数组.match()得到多维数组的结果

var arr = $.map($("#fruit-list [data-fruit]"), function(el) {
  return Array($(el).data("fruit").match(/\w+/g))
});

console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fruit-list" id="fruit-list">
  <span class="chips" title="Click to remove" data-fruit="apple,mango; pineapple, watermelon">every month for 5 times</span>
  <span class="chips" title="Click to remove" data-fruit="banana,kiwi">every May and November for 5 times</span>
</div>