views:

34

answers:

3

I save an array value as attribute of element, but I can't get the attribute value as an array, it's string.

How can I get it as an array?

I will add code for this question.

Thanks.

Code:

<table columnArray="">.....</table>
var columns = $('table > thead > tr > *').map(function(){return {left: $(this).position().left, width: $(this).width()};});
$('table').attr('columnArray', columns.get());
...
...
var columns = $(table).attr('columnArray');

Now columns variable has string value, not array.

+1  A: 

Perhaps you want to use the data function instead.

$('#el').data('myArray',[1,2,3]);
var myArray = $('#el').data('myArray'); // [1,2,3]
balupton
Thank you for your quick answer. So attribute can not save massive data like that, right?
Jason Li
@Jason - The value of an attribute cannot be an array. It can only be a string. It *could* be a string that represents an array, but that gets pretty hacky.
Peter Ajtai
@Jason adding onto Peter's reply. All attributes are designed with special use cases in mind in regards to the HTML specification and are thus limited in what they can hold. The HTML5 data attributes are the only instance where you are "allowed" to create your own attributes. If I just use the attribute "asd" that is invalid as it is not specified by the HTML specs. However, the data function will allow anything as it is a pseudo solution.
balupton
A: 

Looks like you are confusing HTML markup and Javascript variables.

Once you store the array, it'll be available to you in your Javascript:

<table>.....</table>

In your seprate JS file:

var columns = $('table > thead > tr > *').map(function(){
    return {
        left: $(this).position().left, 
        width: $(this).width()
    };
});

// You can now use columns in this scope.
Peter Ajtai
+1  A: 
array = $("your selector").attr("your attribute").split(",");
// "abc,def,ghi" gets ["abc", "def", "ghi"]
elektronikLexikon