使用jQuery通过.each()获取数据属性值 [英] Using jQuery to get data attribute values with .each()
本文介绍了使用jQuery通过.each()获取数据属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下带有数据属性的HTML - 我想编写一些jQuery,它将遍历HTML并收集数据属性并将它们放入数组中 - 任何人都可以帮助我,因为我收到错误。
I have the following HTML with data attributes - I want to write some jQuery that will loop through the HTML and collect the data attributes and put them into an array - could anyone assist as I'm getting an error.
ERROR in console log : item.data is not a function
我正在尝试使用data()属性 - 你能看到我做错了吗?
I am trying to use the data() attribute - can you see what I'm doing wrong?
//我的HTML代码
// My HTML code
<span class="winners" data-userid="123" data-position="1" data-fullname="neil">
<span class="winners" data-userid="234" data-position="2" data-fullname="Ron">
<span class="winners" data-userid="421" data-position="3" data-fullname="Philip">
//我的jQuery代码
// My jQuery code
var multi = $('.winners');
var winners_array = [];
$.each(multi, function (index, item) {
winners_array.push( {name: 'fullname', value: item.data('fullname')} );
});
console.log(winners_array);
// ERROR in console log : item.data is not a function
推荐答案
item
不是jQuery对象,每个
的参数是索引和本机DOM元素
item
is not a jQuery object, the arguments for each
are the index and the native DOM element
var multi = $('.winners');
var winners_array = [];
$.each(multi, function (index, item) {
winners_array.push( {name: 'fullname', value: $(item).data('fullname')} );
});
使用地图会更容易
var winners_array = $.map($('.winners'), function(el) {
return {name: 'fullname', value: $(el).data('fullname')}
});
这篇关于使用jQuery通过.each()获取数据属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文