开发者

Javascript array index is a var

I'm working on a website with Jquery tabs dynamically generated. Each tab has an ID.

For the purpose of my script I need to know how many times the user has clicked in a tab.

To record the number of clicks I was thinking of doing an array like this:

var i  = new Array(my_tab_id);
(...)
i[my_tab_id] = 0;

Where my_tab_id dynamically changes depending on the tab we're in. Sadly, it开发者_如何学Python doesn't seem like the value of my_tab_id is translated into the array. I don't have i[5] = 0, i[6] = 0, etc. but rather i[my_tab_id], which doesn't help more than a simple var.

Any advice? Thanks!


In that case you shouldn't use an array, you should use an object, which you can treat like a hash.

var o = {};
var id = 'x';
o[id] = 1;
alert(o[id]);


This should allow you to store the click count onto each tab using the .data() function in jQuery each time a tab is clicked.

$('#example').bind('tabsselect', function(event, ui) {
    var count = parseInt(ui.tab.data("clickCount"));
    if (isNaN(count)) count = 0;
    count++;
    ui.tab.data("clickCount", count);
});


I think I understand your problem.
You are saying that the var i only has one element. This happens because the var i is newly instantiated every time you open a new tab. I'm guessing every tab is a new page or at least is a new context for var i.
If you want to keep an instance of an object (like an array) in between different pages, take a look at jStorage, it allows you to keep data locally on the browser and it makes it easier to maintain context between page loads.
If all tabs are on the same page then the solution is easier, you need to keep the array in a global variable for the page.


Are you sure my_tab_id is an integer when i[my_tab_id] = 0; is called?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜