0

Greeting

Нow to add the associative array to an jquery object?

examples:

<div id = "element"></div>

$('#element').attr('_mynumber', 10);
console.log($('#element').attr('_mynumber'); // OK, _mynumber = 10

$('#element').attr('_myarray', [1,2,3,9,8,7]);
console.log($('#element').attr('_myarray'); // OK, _myarray = 1,2,3,9,8,7

$('#element').attr('_myassoc', {val1: 10, val2: [1,2,3,9,8,7]});
console.log($('#element').attr('_myassoc'); // FAIL, _mynumber = [object Object] (only as string), _mynumber.val1 = undefined
1
  • "All!" that tone is not very welcomed here. But I guess you can use $e.data() Commented Aug 17, 2016 at 8:13

1 Answer 1

2

Use data to store additional information on an element instead of attr.

$('#element').data('_myassoc', {val1: 10, val2: [1,2,3,9,8,7]});
console.log($('#element').data('_myassoc'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="element"></div>

Sign up to request clarification or add additional context in comments.

3 Comments

big thanks! I've just came up with this method. But this method is very effective for frequent use?
That depends on what you mean by frequent. data is basically a getter and setter on an object. It would sure be faster if you build somthing on your own, but it is not slow, because it is pretty simple. @Zhihar
frequency: 5-10 times per second

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.