在AJAX中使用的JQuery数组

I'm not overly confident in my own abilities but here goes. I want JQuery to find the data attribute of all elements with a particular class. Then I want it to add them to the ajax dataString array.

There are 6 elements with that class all of which have the data attribute. Rather then include them all by id attributes surely their is an easier way. Would this work.

Here goes

var data[] = $('.sidescroller').attr('data');

var dataString = 'function=' + scripts + '&data[]=' + data[];

//execute PHP
$.ajax({
        type: 'POST',
        data: dataString,
         url: '<?php echo $thisposturl;?>?scripts',

Any ideas how to do it.

Marvellous

I think the .attr() function works on the first element among the matched elements a better way would be to use the map function.

var dataArr = [];
$(".sidescroller").map(function(){
    dataArr.push($(this).attr("data"));
});

Firstly, No, .attr() will only get the attributes of the first element in the list

var data = $('.sidescroller').map(function() {
    return $(this).attr('data');
}).get();

Secondly, don't construct query parameters by hand, it's error prone and can also be abused:

Send the data parameter as a set of key-value pairs thus:

data: {
    'function': scripts,
    'data': data
}

According to HTML5 specs. custom data attributes should be named like this: data-name. Then you can use .data to fetch the data. Example below:

HTML

<div id="foo" class="has-data" data-test="foo"></div>
<div id="bar" class="has-data" data-test="bar"></div>

JavaScript

var data = {};
$(".has-data").each(function(){
    data[this.id] = $(this).data("test");
});

$.post('/', data);
var dataString = 'function=' + scripts;

$('.sidescroller').each(function() {
    dataString += '&data=' + $(this).attr('data');
}       

//execute PHP
$.ajax({
 type: 'POST',
 data: dataString,
 url: '<?php echo $thisposturl;?>?scripts',

Would this work?

I think what you are looking for is

var data= [];
$('.sidescroller[data]').each(function(){
    data.push($(this).attr('data'))
});
var strdata = data.join(",");
alert(strdata );

You can find a working sample here.