The function I am using now is:
<div class='edit' data-sort='1'></div>
<div class='edit' data-sort='4'></div>
<div class='edit' data-sort='7'></div>
<div id="as"></div>
exist = $('.edit').length;
var valuer=new Array();
if(exist > 1) {
valuer = $('div[data-sort]').attr('data-sort');
$('#as').append(valuer);
}
But the array 'valuer' only captures the first value, appending the number 1 to the div '#as'
How can I capture all of the values, and then append them to the div '#as'?
You need use the .each() for looping each HTML element found on your selector. Like:
// Edit
var list = [];
$('div[data-sort]').each(function(){
// Append to #as
$('#as').append($(this).attr('data-sort'));
// Stores on list
list.push(this);
});
Use jQuery's map() function for this:
$('#as').append($('div[data-sort]').map(function() {
return $(this).attr('data-sort');
}).get().join(','));
The advantage of the map function is that you can also sort your values on the fly as you would any other JavaScript array. For example:
$('#as').append($('div[data-sort]').map(function() {
return $(this).attr('data-sort');
}).get().sort().join(','))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.