We have links inside the block:
<div>
<a href="#" id="james">text</a>
<a href="#" id="katy">text</a>
<a href="#" id="julia">text</a>
</div>
Ids on different links never repeat.
Trying to create separated array in javascript for each link of this block. The problem is, ids everytime change, I have to do it on the fly.
We should get this:
var james = [];
var katy = [];
var julia = [];
Link's id = nam开发者_Go百科e of the new array.
1) How to code this?
2) How to use then id of the link to call an array? So, we have created them, but in javascript I will do something like
$(this).attr("id").push("text"); // on link hover
It doesn't work, what is a true way for this purpose?
You can't dynamically create var
s but you can dynamically add properties to an object. So create a "master" object for this purpose:
var master = {};
$('a').each(function () {
master[this.id] = [];
});
Push to the array like this:
master[this.id].push('text');
Though I have absolutely no idea why you'd want to do this in separate arrays, you can create the arrays (and anything else you want) using javascript's eval() method.
$(document).ready(function(){
$("a").each(function(){
eval("var " + $(this).attr("id") + " = new Array()")
})
})
You can use the eval similarly to push.
Box9's answer is much more sensible IMO though.
As a source: http://www.hiteshagrawal.com/javascript/dynamic-variables-in-javascript
精彩评论