我希望以数组的形式获取子元素的所有数据属性。
我试过
"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]]
答案 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)
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;
答案 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)
答案 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>